gpt4 book ai didi

java - 比较段落中的某些字符串(句子的一部分)

转载 作者:行者123 更新时间:2023-12-02 01:42:06 25 4
gpt4 key购买 nike

我有一张 map ,

HashMap<String,String> dataCheck= new HashMap<String,String>();
dataCheck.put("Flag1","Additional Income");
dataCheck.put("Flag2","Be your own boss");
dataCheck.put("Flag3","Compete for your business");

和一个段落。

String paragraph = "When you have an additional Income, you can be your
own boss. So advertise with us and compete for your business. We help
you get additional income";

所以我想要实现的是,对于Hashmap的每一个成员,我想将它与段落进行比较,找出重复的次数。匹配我的输出必须如下:

标志1 - 2、标志2 - 1、标志3 - 1

所以,基本上,我只是想了解如何将某个字符串与另一组字符串进行比较。

更新:匹配不区分大小写。

最佳答案

您可以使用带有 String.indexOf() 的循环来计算出现次数。

在下面的代码中,您将看到我们循环遍历 HashMap 并将每个条目与我们的段落进行比较。

    HashMap<String, String> dataCheck = new HashMap<String, String>();
dataCheck.put("Flag1", "Additional Income");
dataCheck.put("Flag2", "Be your own boss");
dataCheck.put("Flag3", "Compete for your business");

String paragraph = "When you have an additional Income, you can be your own boss. So advertise with us and compete for your business. We help you get additional income";

// Now, iterate through each entry in the Map
for (Map.Entry<String, String> entry : dataCheck.entrySet()) {

// Keep track of the number of occurrences
int count = 0;

// After finding a match, we need to increase our index in the loop so it moves on to the next match
int startingIndex = 0;

// This will convert the strings to upper case (so our matches are case insensitive
// It will continue looping until we get an an indexOf == -1 (which means no match was found)
while ((startingIndex = paragraph.toUpperCase().indexOf(entry.getValue().toUpperCase(), startingIndex)) != -1) {

// Add to our count
count++;

// Move our index position forward for the next loop
startingIndex++;
}

// Finally, print out the total count per Flag
System.out.println(entry.getKey() + ": " + count);
}
<小时/>

结果如下:

Flag1: 2
Flag2: 1
Flag3: 1

关于java - 比较段落中的某些字符串(句子的一部分),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54319013/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com