patternjavaModerate
String manipulation in Java
Viewed 0 times
manipulationstringjava
Problem
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.
Can this code be improved?
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;
}
}Solution
Just recoded it, doing simply what your explanation said
Except keep the first char if it is 'a' and keep the second char if
it is 'b'.
Since a possible deletion of a character will affect indices, we check the second character before we check the first.
The resulting code is much simpler and readable simply because the extracted method
Except keep the first char if it is 'a' and keep the second char if
it is 'b'.
Since a possible deletion of a character will affect indices, we check the second character before we check the first.
The resulting code is much simpler and readable simply because the extracted method
deleteCharIfNotEqualTo() does away with some code duplication and at the same time heightens readability of the deFront() method, by explaining what is happening.public String deFront(String str) {
StringBuilder builder = new StringBuilder(str);
deleteCharIfNotEqualTo(builder, 1, 'b');
deleteCharIfNotEqualTo(builder, 0, 'a');
return builder.toString();
}
private void deleteCharIfNotEqualTo(StringBuilder builder, int index, char character) {
if (builder.length() > index && character != builder.charAt(index)) {
builder.deleteCharAt(index);
}
}Code Snippets
public String deFront(String str) {
StringBuilder builder = new StringBuilder(str);
deleteCharIfNotEqualTo(builder, 1, 'b');
deleteCharIfNotEqualTo(builder, 0, 'a');
return builder.toString();
}
private void deleteCharIfNotEqualTo(StringBuilder builder, int index, char character) {
if (builder.length() > index && character != builder.charAt(index)) {
builder.deleteCharAt(index);
}
}Context
StackExchange Code Review Q#26068, answer score: 10
Revisions (0)
No revisions yet.