I think this is oddly complicated...though, I'm 99% sure this can be done with a single line of RegEx, I don't know how from the top of my head1.
This can be shortened to a much simpler and shorter solution, without the need of arrays at all.
String input = "hhiii!!! hooowww aaareee yyyooou???";
StringBuilder output = new StringBuilder();
// Append the first character of the string.
// We can also let the loop start at 0, but then
// we'd need an additional if inside the loop, which
// I'd like to avoid.
output.append(input.charAt(0));
// Start the loop at 1, because we already have the first character.
// We can not
for (int idx = 1; idx < input.length(); idx++) {
// Check the current against the previous character.
if(input.charAt(idx) != input.charAt(idx-1)) {
// If it is not the same, append it.
output.append(input.charAt(idx));
}
}
Of course you'd need to protect yourself from invalid input (empty or null String), and it will also break words with allowed double-characters: foobar, tool, support etc.
.
Some further comments on your code:
- Function name: It's not directly visible what the function does. It should be called something along the lines of
removeDoubleChars
or removeMultipleCharacters
.
- Function type: The function shouldn't directly output the result to
System.out
but rather return it.
- Loops: Use appropriate loops, f.e. your
while
should be a for
.
- Variable names: I know it's partly taught, but I get the creeps (or become a Creeper) if I see variables which are named
i
, j
or arr
. Give your variables meaningful names! In any modern language the name of the variable is neither limited nor does it matter for performance. Write your code primarily for humans, and only secondary for machines...the coder which has to maintain your code after you will thank you.
- Whitespaces: Use 'em!
if(str.charAt(i)!=str.charAt(i+1)){
is harder to read then if(str.charAt(i) != str.charAt(i + 1)) {
.
- Code duplication: Avoid duplicate code. In this case it's minor, but the
i++
should be moved outside the if
, so that it's not necessary to have an else
part.
1: But John does.