所以我正在用多种不同的方法编写程序,其中一个方法要求找到第二个字符串从第一个字符串开始的索引
该方法接受两个字符串作为参数,并返回第二个字符串从第一个字符串开始的位置的字符索引。例如:
IN:legos, go
出:2
该方法的不足之处在于,我只能在类中使用和charAt
,substring
而length
从String
其他类方法中不能使用
我目前没有代码,我需要一个如何启动它的想法
编辑:感谢您的帮助,现在我不是在寻找第二个字符串开始的位置的索引,而是要在第二个字符串在第一个字符串的最右边的区域中找到的位置的索引。例如
IN:密西西比州,S S OUT:5
提前致谢
public int indexOf(final String source, final String find) {
// loop from first character to last character that still leaves length of 'find' string available
for(int sourcePos = 0; sourcePos < source.length() - find.length(); sourcePos++) {
boolean found = true;
for(int findPos = 0; findPos < find.length(); findPos++) {
// if the current char is not a match, then mark as not found and break from loop
if(source.charAt(sourcePos) != find.charAt(findPos)) {
found = false;
break;
}
}
if(found) {
return sourcePos;
}
}
// return -1 to indicate the string was not found
return -1;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句