免责声明:这是一道做作业的问题。我正在尝试编写一个
一些规则:
contains(java.lang.String subString)
方法,该方法为自定义的String类返回表示比较字符串在主字符串内的索引的int
值。一些规则:
- 不使用集合类
- 仅允许使用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;
}
测试结果:
原始字符串: asdfg
比较字符串: donkey
结果: -1
[通过]
原始字符串: asdfg
比较字符串: asdfg
结果: 0
[通过]
原始字符串: asdfg
比较字符串: g
结果: 4
[通过]
原始字符串: asasasf
比较字符串: asd
结果: 0
[失败] (应该是-1
)
原始字符串: asasasf
比较字符串: asf
结果: 0
[失败] (应该是4
)
注释反映了代码的意图。但很明显,当它达到第二个for
循环时,逻辑出现了问题,导致上面的结果。但我看不出问题所在。能否请您再看一下?
continue
替换其中一个return
语句吗? - Soundscapereturn index
移到 for 循环之外。只有在循环内部的检查没有返回 -1 时,才会到达该语句。我现在没有带有 IDE 的电脑,所以无法实际尝试...;-) - azurefrog