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

时间:2019-01-23 01:56:07

标签: java 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";

所以我想要实现的是针对Hashmap的每个成员,我想将其与该段落进行比较,并找到许多重复项。匹配“我的输出”必须如下:

标记1-2,标志2-1,标志3-1

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

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

1 个答案:

答案 0 :(得分:2)

您可以将循环与String.indexOf()一起使用来计数发生次数。

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

    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