###StringFunctions
StringFunctions
###StringFunctions
StringFunctions
###StringFunctions
The squeeze ()
method is IMO a little bit over the top. The same can be achieved by using the replaceAll()
method of the String
class by using the regex patter \s
like so
public static String squeeze (String in) {
return in.replaceAll("\\s+","");
}
which looks a lot cleaner.
(削除) The Let me rephrase this: the removeContDupChars()
method is named wrong because it doesn't remove continous duplicate chars but replaces them with a space
char. (削除ここまで)removeContDupChars()
contains misleading comments which lets one assume that it replaces continous duplicated chars by a space
char.
IMO a cleaner way would be to have a replaceContinousDuplicateChars(string in, char replacement)
which is doing exactly what the name implies. Leaving the fomrer removeContDupChars()
method like so
public static String removeContDupChars(String in) {
string result = replaceContinousDuplicateChars(in, ' ');
result = squeeze(result);
return result;
}
public static String replaceContinousDuplicateChars(String in, char replacement) {
String temp = "";
StringBuilder sb = new StringBuilder(in);
int i = 0;
while (i < sb.length()) {
char prevChar = sb.charAt(i);
for (int j = i + 1; j < sb.length(); j++) {
// As long as there are same characters, Replace all the Duplicates
// with Space.
if (prevChar == sb.charAt(j)) {
sb.setCharAt(j, ' ');
} else {
// Where there is a different char, break the inner loop.
break;
}
}
i++;
}
return sb.toString();
}
As you will notice I have added braces
to if..else
to make the indent more prominent. Another reason for braces is, although they might be optional, to prevent the code to become error prone. I have given your variables some space to breathe to make it easier to read.
I have moved the declaration of char prevChar
inside the while
loop and deleted the unused String temp
variable. You should declare your variables as near to their usage. This prevents such unused variables (if you ignore your IDE which usually tells you) and one doesn't need to scroll arround to find that variable.
In addition you shouldn't use abbreviations to name variables/methods or classes because it makes your code harder to read and understand.