I am trying to remove the letter x if it is present as the first or last character of any given string. Why does my code not check strings with length 0 even though I have accounted for it in my code?
I have already tried using an if statement to check if the length is 0 and, if so, to return the original string. I have also tried returning an empty string with the same value.
public String withoutX(String str) {
if (((str.charAt(0)=='x') || str.charAt(str.length()-1) == 'x') && str.length()>=2){
if (str.charAt(0)=='x'){
str = str.substring(1,str.length());
} if (str.charAt(str.length()-1) == 'x'){
str = str.substring(0,str.length()-1);
}
} if (str.length()==1 && str == "x"){
return "";
} if (str.length()==0){
return str;
// the above if statement (length = 0) does not work
} else{
return str;
}
}
The expected result is for it to return the string without the letter x. This has been achieved for all strings, except an empty one, where it says that the index is out of range.