2013-10-16 17 views
-2

我試圖找出多少次一個字符串出現在另一個。對於我的測試,我使用wordOne的「ea」和wordTwo的「Ilikedthebestontheeastbeachleast」。我的輸出爲我的「外觀」變量返回2,它應該存儲wordTwo中出現「ea」的次數。它應該返回3.錯誤的while循環輸出使用indexOf

我試着搞亂變量初始化,並試圖想想數學的不同,但我幾乎沒有想法。

下面是相關的代碼段:

int wordTwoLength = wordTwo.length(); 
    System.out.println(wordTwoLength); 

    while (wordTwoLength > 0) 
    { 
    positionCount = wordTwo.indexOf(wordOne, positionCount); 
    appearances++; 
    wordTwoLength = (wordTwoLength - positionCount); 
    } 
    System.out.println(appearances); 

謝謝!

編輯:我忘了補充一點,我嘗試了其他測試輸入,並得到瘋狂的輸出。它會返回數字高於預期的一些,而低於其他數字。

+2

同樣的問題,有30分鐘http://stackoverflow.com/q/19395153/1031945 –

+0

這是一個不同的問題。如果你讀了它,你會知道。這是不允許的? – coinbird

回答

0

所以現在的問題是.indexOf仍然返回wordTwo中「ea」的真正索引 - 它沒有考慮從哪裏開始。同樣,將positionCount設置爲等於您找到該單詞的位置,然後再從該位置搜索就會立即讓您立即找到該單詞的同一個實例,而不是下一個。

wordTwo中第一個「ea」實例的索引是18,因此wordTwoLength將被設置爲32-18或14.然後,您會在wordTwo中找到相同的ea實例,並且將設置wordTwoLength到14-18或-4。然後,你會退出while循環,一同亮相爲2。

+0

這很有道理。我將嘗試修改wordOne長度的positionCount變量。這樣它將開始2個職位,跳過剛剛看到的單詞。 謝謝! – coinbird

0
for (int index = 0; (index = wordTwo.indexOf(wordOne, index)) > -1; index ++) 
    appearances ++; 
0

您可以通過「轉換字符串的字符數組」。因爲這將是更有效的(我認爲)。我已經提供了簡化上述工作這裏的示例代碼,

String wordOne="Ilikedthebestontheeastbeachleast"; 
String wordTwo="ea"; 
int count=0; 
char[] arrayOne=wordOne.toCharArray(); 
char [] arrayTwo=wordTwo.toCharArray(); 
for(int i=0;i<=((arrayOne.length)-1);i++) 
{ 
if(arrayTwo[0]==arrayOne[i]&&arrayTwo[1]==arrayOne[i+1]) 
count+=1; 
} 
System.out.println("Pattern found "+count+" times."); 

這將適合您的需要,但使用For循環。

0

試試這個簡單的代碼:

class Demo{ 
public static void main(String[] args){ 
    String wordOne = "ea"; 
    String wordTwo = "Ilikedthebestontheeastbeachleast"; 
    String[] arr = wordTwo.split(wordOne); 
    int cnt = arr.length - 1; 
    System.out.printf("[%s] has occured for %s time(s) in [%s]", wordOne, cnt, wordTwo); 
} 

}

+0

我們還沒有了解.split。謝謝你。 – coinbird

+0

試一試,其簡單。 http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#split(java.lang.String) – Arvind