First, is this part correct?
} else if (str.length() == 1 && str.charAt(0) == 'a') {
return str;
} else {
return str;
}
This will return a string of length 1, unchanged, regardless of the character. What should happen if you pass "z"? Since the first character is not 'a', should it be removed?
I suspect it was supposed to be something like this:
} else if (str.length() == 1 && str.charAt(0) != 'a') {
return "";
} else {
return str;
}
The rest of this answer assumes it should remove the character
You could use a StringBuilder
and delete the characters as necessary:
public String deFront(String str) {
StringBuilder sb = new StringBuilder(str);
if (sb.length() > 1 && sb.charAt(1) != 'b') {
sb.deleteCharAt(1);
}
if (sb.length() > 0 && sb.charAt(0) != 'a') {
sb.deleteCharAt(0);
}
return sb.toString();
}
Or you could use a regular expression search & replace:
public String deFront(String str) {
str = str.replaceFirst("^(.)[^b]", "$1");
str = str.replaceFirst("^[^a]", "");
return str;
}