2016-09-20 80 views
1

我正在尝试查找句子中出现单词的总次数。 我尝试下面的代码:如何获得句子中出现的单词总数

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.

谢谢。

+0

用'lastIndex + = indexWord.length();'替换'lastIndex + = findStr.length();' – qxz

+0

great.its现在工作正常。感谢您节省我的时间。 –

+0

我将添加一个答案,以便将此问题标记为已解决 – qxz

回答

0

当您在匹配后增加lastIndex时,意思是按匹配的长度(indexWord)递增,而不是输入字符串的长度(findStr)。只需更换线路

lastIndex += findStr.length(); 

lastIndex += indexWord.length(); 
0

试试这个代码

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); 
0

您可以使用地图这一点。

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); 
    } 
0

是否有任何原因没有使用现成的API解决方案。 这可以通过使用apache中的StringUtils来实现-lang有CountMatches方法来统计另一个String中出现的次数。

E.g.

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); 
} 
相关问题