我想統計出源字符串中特定單詞的出現次數。 假設src =「thisisamangoterrthisismangorightthis?」 word =「this」 所以我正在做的是,首先搜索src中的單詞索引。它在索引0處。現在我從這個索引位置提取部分到src結尾。 即現在src =「isamangoterrthisismangoright這是什麼?」並再次搜索單詞。 但我越來越數組越界的異常。計算java中單詞出現的次數
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,因此它保持了第一個字符串的長度,即使S1變得越來越小,這說明你的異常。只需使用substring(int)從給定索引切換到字符串結尾。 –