简体   繁体   中英

I can't see the point of this two lines of code

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;
    }   

here comes my question what is the point of these loops why the start and end like that the for loop (TextCounter < TextLength - MyWordLengt) the while loop ( while (WordCounter < MyWordLength && this.Text[TextCounter + WordCounter] == this.MyWord[WordCounter] )

The point is: Textcounter starts looking at the the array containing the whole text, and for each characater of the text, which are stored in the array Text[], looks for the next letters, and checks if they match the same sequence of letters of the array MyWord[], which contains the word, and if every char match, then it returns the position in the text where the matching word is

The only problem is that the world i'm looking for is for example (champ), if in the text there is a word (championship) it will say that they match, but it should say they don't

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM