繁体   English   中英

如何获得句子中单词出现的总数

[英]How to get the total count of occurence of a word in a sentence

我试图找到句子中单词出现的总数。 我尝试了以下代码:

String str = "This is stackoverflow and you will find great solutions  here.stackoverflowstackoverflow is a large community of talented coders.It hepls you to find solutions for every complex problems.";

    String findStr = "hello World";     
    String[] split=findStr.split(" ");

    for(int i=0;i<split.length;i++){
        System.out.println(split[i]);
        String indexWord=split[i];
        int lastIndex = 0;
        int count = 0;      
        while(lastIndex != -1){

            lastIndex = str.indexOf(indexWord,lastIndex);
            System.out.println(lastIndex);

            if(lastIndex != -1){
                count ++;
                lastIndex += findStr.length();
            }

        }
        System.out.println("Count for word "+indexWord+" is : "+count);
    }

如果我传递字符串像“堆栈解决方案”,字符串应该被分成两个(空格分割),并且需要找到句子中每个字符串的出现次数。如果我只传递一个单词,则计数是完美的。必须匹配包含搜索字符串的子串。 例如: - 在句子“堆叠”中出现三次,但计数只有2。

谢谢。

在匹配后递增lastIndex ,意味着将其增加匹配的长度( indexWord ),而不是输入字符串的长度( findStr )。 只需更换线

lastIndex += findStr.length();

lastIndex += indexWord.length();

试试这段代码

String str = "helloslkhellodjladfjhello";
String findStr = "hello";
int lastIndex = 0;
int count = 0;

while(lastIndex != -1){

lastIndex = str.indexOf(findStr,lastIndex);

 if(lastIndex != -1){
    count ++;
    lastIndex += findStr.length();
 }
}
System.out.println(count);

你也可以使用map。

public static void main(String[] args) {

        String value = "This is simple sting with simple have two occurence";

        Map<String, Integer> map = new HashMap<>();
        for (String w : value.split(" ")) {
            if (!w.equals("")) {

                Integer n = map.get(w);
                n = (n == null) ? 1 : ++n;
                map.put(w, n);
            }
        }
        System.out.println("map" + map);
    }

是否有任何理由不使用现成的API解决方案。 这可以通过在apache commons-lang中使用StringUtils来实现,它具有CountMatches方法来计算一个String在另一个String中出现的次数。

例如

String input = "This is stackoverflow and you will find great solutions  here.stackoverflowstackoverflow is a large community of talented coders.It hepls you to find solutions for every complex problems.";
String findStr = "stackoverflow is";
for (String s : Arrays.asList(findStr.split(" "))) {
         int occurance = StringUtils.countMatches(input, s);
         System.out.println(occurance);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM