"在char []中查找子字符串"获得意外结果

Sou*_*ape 6 java arrays methods char

免责声明:这是一个功课问题.我正在尝试编写一个contains(java.lang.String subString)方法,该方法返回一个int表示主字符串中比较字符串索引的值,用于定制的String类.

一些规则:

  • 没有收集课程
  • java String类中只允许使用charAt()和toCharArray()(但允许来自其他类的方法)
  • 假设length()返回主字符串的长度(这正是它的作用)

我的代码:

public int contains(java.lang.String subString) {
    this.subString = subString;
    char[] arrSubStr = this.subString.toCharArray();
    //Create initial fail
    int index = -1;
    //Make sure comparison subString is the same length or shorter than the primary string
    if(arrSubStr.length > length()) {
        return index;
    }
    //Steps to perform if initial conditions are met
    else {
        //Compare first character of subString to each character in primary string
        for(int i = 0; i < length(); i++) {
            //When a match is found...
            if(arrSubStr[0] == this.content[i]) {
                //...make sure that the subString is not longer than the remaining length of the primary string
                if(arrSubStr.length > length() - i) {
                    return index;
                }
                //Proceed matching remainder of subString
                else {
                    //Record the index of the beginning of the subString contained in primary string
                    index = i;
                    //Starting with second character of subString...
                    for(int j = 1; j < arrSubStr.length;) {
                        //...compare with subsequent chars of primary string, 
                        //and if a failure of match is found, reset index to failure (-1)
                        if(arrSubStr[j] != this.content[j+i]) {
                            index = -1;
                            return index;
                        }
                        //If we get here, it means whole subString match found
                        //Return the index (=i) we set earlier
                        else {
                            return index;
                        }
                    }
                }
            }
        }
    }
return index;
}
Run Code Online (Sandbox Code Playgroud)

测试结果:

主字符串:asdfg
比较字符串:donkey
结果:-1[PASS]

主字符串:asdfg
比较字符串:asdfg
结果:0[PASS]

主字符串:asdfg
比较字符串:g
结果:4[PASS]

主字符串:asasasf
比较字符串:asd
结果:0[ FAIL ](应该是-1)

主字符串:asasasf
比较字符串:asf
结果:0[ FAIL ](应该是4)

这些评论反映了代码的工作方式.然而很明显,当它到达第二个for循环时,逻辑会以某种方式分解以给出上面的结果.但我看不出问题.我可以第二眼看到这个吗?

Yas*_*jaj 1

//If we get here, it means whole subString match found
//Return the index (=i) we set earlier
else {
    return index;
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,这个假设并不正确。如果到达那里,则意味着两个子字符串的第二个字符相同,因为该if-else语句只会执行一次并且两端都包含return.

既然我已经诊断出问题,解决这个问题的方法可能很简单,但我想进一步解决这个问题。我们每天尝试编写代码的方式是我们使用的代码可以维护、可重用和可测试的方式。

这基本上意味着我们这里的函数可以很容易地分割成不同的小函数,一个接一个地调用,我们可以为其编写单元测试并接收关于一组逻辑语句是否合适的快速反馈。