我正在编写一个方法,如果其中一个字符串出现在另一个字符串的最后,并且字符串不同,则返回true.我们不能使用endsWith()
例如:
如果a ="all"且b ="ball",则该方法将返回true.
如果a ="是"并且b ="是",则该方法将返回false.
这是我到目前为止所做的,但它一直说字符串索引超出范围= -1
public static boolean startOther(String a, String b){
if(a.equals(b))
return false;
int pos=a.indexOf(b);
int pos1=b.indexOf(a);
int len=a.length();
int len1=b.length();
if(pos>-1 && a.substring(len-pos).equals(b)|| pos1>-1 && b.substring(len1-pos1).equals(a))
return true;
return false;
}
Run Code Online (Sandbox Code Playgroud)
这有点“三思而后行”,但你想做的是:
如果你进行任何类型的减法,你都不会得到正确的子串大小;也就是说,如果减去要检查的字符串的长度,则只会得到一个字符。
public static boolean startOther(String left, String right) {
if (left == null || right == null || left.equals(right)) {
return false;
}
int rightSubstringInLeft = left.indexOf(right);
int leftSubstringInRight = right.indexOf(left);
if(rightSubstringInLeft != -1) {
return left.substring(rightSubstringInLeft).equals(right);
} else if(leftSubstringInRight != -1) {
return right.substring(leftSubstringInRight).equals(left);
} else {
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
正如评论中指出的,这是相同代码的更优化形式。基本上它是相同的,但是您不需要对子字符串执行另一个等于检查,因为lastIndexOf
只会为您提供整个子字符串的最后一个索引。
public static boolean startOther(String left, String right) {
if (left == null || right == null || left.equals(right)) {
return false;
}
int rightSubstringInLeft = left.lastIndexOf(right);
int leftSubstringInRight = right.lastIndexOf(left);
if(rightSubstringInLeft != -1) {
return rightSubstringInLeft == left.length() - right.length();
} else if(leftSubstringInRight != -1) {
return leftSubstringInRight == right.length() - left.length();
} else {
return false;
}
}
Run Code Online (Sandbox Code Playgroud)