소스 문자열에서 특정 단어가 나오는 횟수를 계산하고 싶습니다. 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;
}
당신은 LEN1을 다시 계산하지 문자열에서 단어를 계산하기 위해보십시오. 주어진 인덱스에서 문자열의 끝까지 자르는 substring (int)을 사용하면된다. –