I'm attempting to create a method which will take a char array, cut out any duplicate spaces (2 or more) and then place '\u0000'
characters at the end for however many spaces were cut out so that the array length is satisfied. I realize I have to shift the elements down but this is where I'm having trouble. My program works fine with 2 spaces but a sequence of three in a row will throw it off. I understand why this is happening but I don't know how to fix it. I know it stems from the code characters[j] = characters[j+1]
but I don't know how to go about fixing it.
int duplicateCount = 0;
// Create a loop to read the element values
for(int i = 0; i + 1 < characters.length; i++){
// If the element is a space and the next one is a space
if(characters[i] == ' ' && characters[i+1] == ' '){
// Add to duplicate count and start shifting values down
duplicateCount++;
// *THIS IS WHERE I THINK BUG IS*
for(int j = i; j < characters.length - 1; j++){
characters[j] = characters[j+1];
}
}
}
// Replace characters at end with how many duplicates were found
for(int replace = characters.length - duplicateCount; replace < characters.length; replace++){
characters[replace] = '\u0000';
}
}
Thank you all.