2016-09-20 17 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つ(スペース分割)に分割し、文の中で、各文字列の発生のないを見つける必要があるべきではありません。私は1つの単語を渡す場合、カウントは完璧です。コードは、検索された文字列を含む部分文字列にも一致する必要があります。 例: - 文章で「スタック」のApperが3回カウントされますが、カウントは2だけです。

ありがとうございました。

+0

'lastIndex + = findStr.length();を' lastIndex + = indexWord.length(); 'に置き換えますか? – qxz

+0

great.itsはうまくいきました。時間を節約してくれてありがとう。 –

+0

回答を追加して、この質問に解決済みとマークすることができます – qxz

答えて

0

一致後にlastIndexを増やすと、入力語の文字列(findStr)の長さではなく、一致の長さ(indexWord)だけ増やすことを意味します。ただ、あなたにも、このためにはマップを使用することができ、このコード

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

でライン

lastIndex += findStr.length(); 

を交換してください。

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

を試してみてください

lastIndex += indexWord.length(); 
0

レディメイドAPIソリューションを使用しない理由はありますか。 これは、1つのStringの出現回数を別のものに数えるために、CountMatchesメソッドを持つApacheのCommons-langのStringUtilsを使用することで実現できます。

など。

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); 
} 
関連する問題