This is my second post on this same method. The description of the method is as follows:
"Reduces all sequences of 2 or more spaces to 1 space within the characters array. If any spaces are removed then the same number of Null character '\u0000' will fill the elements at the end of the array."
The parameter for the method is a char array. I've succeeded in counting the amount of duplicate spaces, however, I cannot for the life of me figure out how to shift values down while accounting for such duplicate spaces. At the end, the method is supposed to replace the number of indexes of duplicate spaces with '\u0000' characters. This is what I have so far:
// Calculate duplicate count before changing the array
int duplicateCount = 0;
for(int i = 0; i + 1 < characters.length; i++){
if(characters[i] == ' ' && characters[i + 1] == ' '){
duplicateCount++;
}
}
// Shift the array down however much is needed
for(int j = 0; j + 1 < characters.length; j++){
if(characters[j] == ' ' && characters[j + 1] == ' '){
for(int a = j, b = a + 1; b < characters.length; a++, b++){
characters[a] = characters[b];
}
}
}
for(int replace = characters.length - duplicateCount; replace < characters.length; replace++){
characters[replace] = '\u0000';
}
}
Thus, if the input was:char [] characters = {'a', 't', ' ', '.', ' ', ' ', 'g', ' ', ' ', 'h', ' '};
The output should be: char [] expectedResult = {'a', 't', ' ', '.', ' ', 'g', ' ', 'h', ' ','\u0000', '\u0000'};
Thank you folks, this problem seems like it should be so simple yet I'm stuck. If you can offer any explanation to your answer, I'd very much appreciate it. Thank you again.
charactersarray to that of the new array, no copying necessary