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을 증가 시키면 입력 단어 문자열 길이 (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 솔루션을 사용하지 않는 이유가 있습니까? 아파치의 Commons-lang에있는 StringUtils를 사용하여 CountMatches 메서드를 사용하여 한 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); 
} 
관련 문제