2016-09-20 2 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); 
    } 

Если я передаю строку, как «решение стеки», то строка должна быть разделена на два (пространства раскола) и не нужно, чтобы найти не появление каждой строки в предложении . Счет отлично, если я передаю только одно слово. Код должен соответствовать даже подстрокам, содержащим искомую строку. Например: - В предложении «стек» apperars три раза, но счет только 2.

Спасибо.

+0

Заменить 'lastIndex + = findStr.length();' с 'lastIndex + = indexWord.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 на месте. Это можно сделать, используя StringUtils в apache commons-lang, используя метод CountMatches, чтобы подсчитывать количество вхождений одной строки в другую.

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); 
} 
Смежные вопросы