2016-05-16 41 views
0
public class BruteForceSearch { 


    private char[] Text; 
    private char[] MyWord; 
    private int TextLength; 
    private int MyWordLength; 


    //word or -1 if not found 
    public int search(String Text, String MyWord) { 

     //chars 
     this.Text = Text.toCharArray(); 
     this.MyWord = MyWord.toCharArray(); 
     this.TextLength = Text.length(); 
     this.MyWordLength = MyWord.length(); 


     for (int TextCounter = 0; TextCounter < TextLength - MyWordLength; TextCounter++) { 


      int WordCounter = 0; 

      //matched increament WordCounter 
      while (WordCounter < MyWordLength && this.Text[TextCounter + WordCounter] == this.MyWord[WordCounter]) { 
       WordCounter++; 
      } 

      if (WordCounter == MyWordLength) { 
       return TextCounter; 
      } 

     } 
     // return -1 in case you didn't find the word 
     return -1; 
    } 

在這裏我的問題是什麼是這些循環 爲什麼開始和結束這樣 for循環(TextCounter < TextLength - MyWordLengt) while循環的點(while (WordCounter < MyWordLength && this.Text[TextCounter + WordCounter] == this.MyWord[WordCounter]我看不到這個代碼兩行的點

+4

你問for循環什麼是?我沒有看到你對此感到困惑。 – Gendarme

+0

我很擔心我的愚蠢的問題,抱歉,但我認爲人們會幫我althoughmy愚蠢:d但我問的邏輯不是這樣,對於循環工作 –

回答

0

關鍵是: Textcounter開始查看包含整個文本的數組,並且對於存儲在數組Text []中的每個文本字符,查找下一個字母,並檢查它們是否匹配陣列MyWord [],其中包含字,並且如果每一個字符匹配的字母相同的序列,則它返回在t時的位置他的文字在哪裏匹配的字是

唯一的問題是,我期待的世界是例如(冠軍),如果在文本中有一個詞(冠軍),它會說他們匹配,但它應該說他們不

+0

他爲什麼這樣做(正文長度 - MyWordLength),但如果讓這文本長度將工作 –

+0

另一件事從TextLength減去MyWordLength假設我們有TextLength 10和MyWordLength 5 for循環將從0開始到4並且不完成整個文本,但最奇怪的事情,這確實工作:D –

+0

AHAH, 因爲如果你的話是一個長度爲5的,其長度爲10的for循環文本中去,直到10 - 5,這意味着直到4位像你所說的, 但你有這行代碼 WordCounter < MyWordLength && this.Text [TextCounter + WordCounter] 多虧了這一點,你從該位置4走到位置9(因爲大小爲10的數組從位置0到9) –