I'm trying to reduce consecutive elements of array to one, but not for all values like:
{3,0,0,0,3,3,3,0,0,0} => {3,0,3,0}
but for specific one, in my example 0:
{3,0,0,0,3,3,3,0,0,0} => {3,0,3,3,3,0}
so only zeros (the threes are intact) are reduced.
I have Java String working code I wrote:
public static String removeConsecutive(String str, char remove) {
char[] chars = str.toCharArray();
int current = 0;
int result = current;
while (current < chars.length) {
if (chars[current] == remove) {
// keep the first occurrence
chars[result++] = chars[current++];
// ignore the others
while (current < chars.length && chars[current] == remove) {
++current;
}
} else {
chars[result++] = chars[current++];
}
}
return new String(chars, 0, result);
}
and it does the trick:
public static void main(String[] args) {
System.out.println(removeConsecutive("000300300030303330000", '0'));
}
outputs: 0303030303330
Can anyone suggest any improvements, since it think the code is not perfect. It's doesn't have to be String in use, but with any other array.