It's a bit of "look before you leap", but what you want to do is:
- Check the index location of each string within another.
- If (and only if) the index location exists, check to see if the substring from that index spot all the way to the end matches.
- Otherwise, return false.
If you do any sort of subtraction, you're not going to get the correct size of substring; that is, if you subtract the length of the string you're checking against, you're only going to get one character.
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;
}
}
Here's a more optimized form of the same code, as pointed out in the comments. Fundamentally it's the same, but you don't need to perform another equals check on the substring, since lastIndexOf would only ever give you the last index of the whole substring.
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;
}
}