Here is the question followed by my working program:
Given a string, return a version without the first 2 chars. Except keep the first char if it is 'a' and keep the second char if it is 'b'. The string may be any length. Harder than it looks.
deFront("Hello") → "llo" deFront("java") → "va" deFront("away") → "aay"
Can this code be improved?
public String deFront(String str) {
if (str.length() >= 2) {
char firstCharacter = str.charAt(0);
char secondCharacter = str.charAt(1);
if (firstCharacter == 'a' && secondCharacter == 'b') {
// donot skip
return str;
} else if (firstCharacter == 'a' && secondCharacter != 'b') {
// skip first character only
return str.substring(0, 1) + str.substring(2);
} else if (firstCharacter != 'a' && secondCharacter == 'b') {
// skip second character only
return str.substring(1);
} else {
return str.substring(2);
}
} else if (str.length() == 1 && str.charAt(0) == 'a') {
return str;
} else {
return str;
}
}