I am coding the following interesting problem :
Remove '_' and print with 1 space from a given string For example, for "w_e_b__services" output should be : "w e b services". Multiple underscore should be substituted with only with one space.
The following is my code, which has some code duplication. I can see there are some ways to get rid of that duplication but that complicates the code in a different way. It would be great to get some code review on this.
public class ReplaceUnderscore {
private static final char UNDERSCORE = '_';
private static final char SPACE = ' ';
public static String replace(String input) {
if (input.isEmpty()) {
return input;
}
StringBuilder output = new StringBuilder();
char prevChar = input.charAt(0);
if (prevChar == UNDERSCORE) {
output.append(SPACE);
} else {
output.append(prevChar);
}
for (int i = 1; i < input.length(); i++) {
char currentChar = input.charAt(i);
if (currentChar == UNDERSCORE) {
if (currentChar != prevChar) {
output.append(SPACE);
}
} else {
output.append(currentChar);
}
prevChar = currentChar;
}
return output.toString();
}
}
And here is the junit test:
public class StripUnderscoreTest {
@Test
public void strip() throws Exception {
assertEquals(" ", ReplaceUnderscore.replace("_"));
assertEquals("a b c", ReplaceUnderscore.replace("a_b_c"));
assertEquals("a b c", ReplaceUnderscore.replace("a__b__c"));
assertEquals("a b c", ReplaceUnderscore.replace("a___b___c"));
}
}