2016-09-20 81 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); 
} 
相關問題