2014-03-31 5 views
1

소스 문자열에서 특정 단어가 나오는 횟수를 계산하고 싶습니다. src = "thisisamangoterthisismangoright thisis?"라고 가정 해 보겠습니다. word = "this" 내가하고있는 일은 src에서 단어 색인을 먼저 검색하는 것입니다. 그것은 인덱스 0에 있습니다. 이제이 인덱스 위치에서 src 끝으로 파트를 추출합니다. 즉, src = "isamangoterrthisismangoright this is this?" 다시 단어를 검색하십시오. 그러나 배열 밖 예외가 나타납니다. 당신이 ArrayIndexOutOfBoundsException를 throw하는 방법을 사용하는 경우자바에서 단어의 발생 횟수를 카운트

public static int countOccur(String s1, String s2) 
{ 
    int ans=0; 
    int len1=s1.length(); 
    int len2=s2.length(); 
    System.out.println("Lengths:"+len1+" " +len2); 

    while(s1.contains(s2)) 
    { 
     ans++; 
     int tmpInd=s1.indexOf(s2); 
     System.out.println("Now Index is:"+tmpInd); 
     if((tmpInd+len2)<len1){ 
      s1=s1.substring(tmpInd+len2, len1); 
      System.out.println("Now s1 is:"+s1); 
     } 
     else 
      break; 
    } 
    return ans; 

} 
+0

당신은 LEN1을 다시 계산하지 문자열에서 단어를 계산하기 위해보십시오. 주어진 인덱스에서 문자열의 끝까지 자르는 substring (int)을 사용하면된다. –

답변

0

는 S1 당신의 예외를 설명하는, 작아에도 불구하고, 그것은 첫 번째 문자열의 길이를 유지 있도록

private static int countingWord(String value, String findWord) 
    { 
     int counter = 0; 
     while (value.contains(findWord)) 
     { 
      int index = value.indexOf(findWord); 
      value = value.substring(index + findWord.length(), value.length()); 
      counter++; 
     } 
     return counter; 
    } 
0

는 항상 경계를 확인하는 것이 좋습니다. String#substring 참조 :

경우 IndexOutOfBoundsException - beginIndex가 부의 경우, 또는 endIndex 이 String 객체의 길이보다 큰 경우, 혹은 beginIndexendIndex보다 큰 경우. 더 나은, 당신은 처음부터 이러한 상황을 피하기 위해 논리를 고려해야합니다

if(tmpInd + len2 >= s1.length() || len1 >= s1.length() || ...) { 
    //Not good 
} 

또는 :


당신은 모든 경우를 포함해야한다.

0

시험 후 indexOf()를 사용, 그것은 당신을 위해 경계 등의 돌볼 것입니다 :

public static int countOccurrences(final String haystack, final String needle) 
{ 
    int index = 0; 
    int ret = 0; 
    while (true) { 
     index = haystack.indexOf(needle, index); 
     if (index == -1) 
      return ret; 
     ret++; 
    } 

    // Not reached 
    throw new IllegalStateException("How on earth did I get there??"); 
} 
0

당신의 문자열에 substring을하는 것은이 방법

public int indexOf(int ch, int fromIndex) 
를 사용하는 대신 는

는 단지 결과 있는지 확인 is -1

0

대체품을 사용하여 문제를 해결할 수도 있습니다.

String s = "thisisamangoterrthisismangorightthis?"; 
String newS = s.replaceAll("this",""); 
int count = (s.length() - newS.length())/4; 
+0

나는 XD를 이런 방식으로하고 싶지만''this''에 변수를 넣고 count 계산에 사용한다.) –

+0

여기에서 리터럴 텍스트를 대체하기 때문에'.replaceAll()'대신'.replace()'를 사용하라. 이름에서 알 수있는 것과는 달리, .replace()'_does_는 모든 어커런스를 바꿉니다. 그러나 새로운 문자열 생성을 필요로하지 않는 솔루션이 존재할 때 왜 시작해야할까요? ;) – fge

0
import java.io.*; 
import java.util.*; 

public class WordCount 
{ 
public static class Word implements Comparable<Word> 
{ 
    String word; 
    int count; 

    @Override 
    public int hashCode() 
    { 
     return word.hashCode(); 
    } 

    @Override 
    public boolean equals(Object obj) 
    { 
     return word.equals(((Word)obj).word); 
    } 

    @Override 
    public int compareTo(Word b) 
    { 
     return b.count - count; 
    } 
} 


    public static void findWordcounts(File input)throws Exception 
    { 
     long time = System.currentTimeMillis(); 

    Map<String, Word> countMap = new HashMap<String, Word>(); 

    BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(input))); 
    String line; 
    while ((line = reader.readLine()) != null) { 
     String[] words = line.split("[^A-ZÅÄÖa-zåäö]+"); 
     for (String word : words) { 
      if ("".equals(word)) { 
       continue; 
      } 

      Word wordObj = countMap.get(word); 
      if (wordObj == null) { 
       wordObj = new Word(); 
       wordObj.word = word; 
       wordObj.count = 0; 
       countMap.put(word, wordObj); 
      } 

      wordObj.count++; 
     } 
    } 

    reader.close(); 

    SortedSet<Word> sortedWords = new TreeSet<Word>(countMap.values()); 
    int i = 0; 
    for (Word word : sortedWords) { 
     if (i > 10) { 
      break; 
     } 

     System.out.println("Word \t "+ word.word+"\t Count \t"+word.count); 

     i++; 
    } 

    time = System.currentTimeMillis() - time; 

    System.out.println("Completed in " + time + " ms"); 
    } 


public static void main(String[] args)throws Exception 
{ 
    findWordcounts(new File("./don.txt"));    
} 
} 
관련 문제