I am trying to create a method that will take a char array, cut out any duplicate spaces (2 or more), and then put the characters '\u0000'at the end, however many spaces would be cut out so that the length of the array is satisfied. I understand that I need to push the elements down, but this is where I have problems. My program works fine with 2 spaces, but a sequence of three in a row will throw it out. I understand why this is happening, but I do not know how to fix it. I know this is related to the code characters[j] = characters[j+1], but I do not know how to fix it.
int duplicateCount = 0;
for(int i = 0; i + 1 < characters.length; i++){
if(characters[i] == ' ' && characters[i+1] == ' '){
duplicateCount++;
for(int j = i; j < characters.length - 1; j++){
characters[j] = characters[j+1];
}
}
}
for(int replace = characters.length - duplicateCount; replace < characters.length; replace++){
characters[replace] = '\u0000';
}
}
Thanks to everyone.
source
share