问题
I want to count the number of occurrences of particular word in a source string. Let's say src="thisisamangoterrthisismangorightthis?" word="this" So what I am doing is, first search for index of word in src. It's at index 0. Now I am extracting the part from this index location to end of src. i.e., now src="isamangoterrthisismangorightthis?" and search for word again. But I am getting array out of bound exception.
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;
}
回答1:
Try this to count the word in a string,
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;
}
回答2:
When you use a method that throws ArrayIndexOutOfBoundsException, it's always a good idea to check the bounds. See String#substring:
IndexOutOfBoundsException - if the
beginIndexis negative, orendIndexis larger than the length of this String object, orbeginIndexis larger thanendIndex.
You should cover all cases:
if(tmpInd + len2 >= s1.length() || len1 >= s1.length() || ... ) {
//Not good
}
Or, better, you should consider your logic to avoid this situation in the first place.
回答3:
Try and use indexOf(), it will take care of bounds etc for you:
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??");
}
回答4:
Rather than doing a substring on your String use this method
public int indexOf(int ch, int fromIndex)
then just check if the result is -1
回答5:
Your might use replace to solve the problem
String s = "thisisamangoterrthisismangorightthis?";
String newS = s.replaceAll("this","");
int count = (s.length() - newS.length()) / 4;
回答6:
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"));
}
}
来源:https://stackoverflow.com/questions/22755915/counting-number-of-occurrences-of-word-in-java