2016-05-16 39 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) –