Reputation: 11
"Given two strings, return true if either of the strings appears at the very end of the other string, ignoring upper/lower case differences (in other words, the computation should not be "case sensitive")."
When I put the two variables through testing, the substring is equal to the shorter of the two strings, but it still returns false in my if statement.
This is my attempt at the solution on coding bat regarding strings. I've stored the strings as new strings to eliminate case sensitivity. The link can be found here for reference.1
public boolean endOther(String a, String b) {
String x = a.toLowerCase();
String y = b.toLowerCase();
int xl = a.length();
int yl = b.length();
if(xl > yl && x.substring(yl, xl).equals(y)) return true;
if(xl < yl && y.substring(xl, yl).equals(x)) return true;
if(xl == yl && x.equals(y)) return true;
else return false;
}
Upvotes: 0
Views: 177
Reputation: 56393
the overloaded version of the substring you're using is unnecessary considering all you have to do is check if one of the strings ends with the other.
xl
is greater than yl
, all you have to do is
x.substring(xl-yl).equals(y)
, meaning your substring should start at xl-yl
until the end of the String
.xl
is less than yl
, all you have to do is y.substring(yl-xl).equals(x)
, meaning your substring should start at yl-xl
until the end of the String
.full solution:
public boolean endOther(String a, String b) {
String x = a.toLowerCase();
String y = b.toLowerCase();
int xl = a.length();
int yl = b.length();
if(xl > yl && x.substring(xl-yl).equals(y)) return true;
if(xl < yl && y.substring(yl-xl).equals(x)) return true;
if(xl == yl && x.equals(y)) return true;
else return false;
}
However, as mentioned within the comments you're better off using String#endsWith.
Upvotes: 2