The following code (from "Cracking the code interview", from Gaale Laakman), shows how to remove duplicate characters in a char array without using a copy of the array to avoid some extra memory use. It re-writes the final characters in the first array with an offset. Since the final array is smaller than the previous one, a null character is set at the position following the final characters, as if to say the array stops there:
str[tail] = 0;
I was wondering if by doing this the variable "length" of the array gets changed. If not, I don't understand why this example works. Or is this just an example where we would check where is the null character to find the length of the array and don't use the length variable in question?
Here is the whole code:
public static void removeDuplicates(char[] str) {
if (str == null) return;
int len = str.length;
if (len < 2) return;
int tail = 1;
for (int i = 1; i < len; ++i) {
int j;
for (j = 0; j < tail; ++j) {
if (str[i] == str[j]) break;
}
if (j == tail) {
str[tail] = str[i];
++tail;
}
}
str[tail] = 0;
}