Home > Back-end >  Replacing Duplicates in Character Array with placeholder character ' '?
Replacing Duplicates in Character Array with placeholder character ' '?

Time:03-13

For any string of characters I input to my charArray, this simply returns the first character and the rest as spaces. Why? I simply want to replace all of the non-original renditions of a character with a space.

for (int i = 0 ; i<charArray.length ; i  ) {
                        for (int j = 1 ; j<charArray.length ; j  ) {
                            if (charArray[i] == charArray[j])
                                charArray[j] = ' ';
                            
                        }
                    }

CodePudding user response:

Your inner loop needs to start at i 1 instead of the hardcoded value 1:

char[] charArray = "abcdabce".toCharArray();
        
for (int i = 0; i < charArray.length; i  )
{
    // check if a space was already inserted at this index
    if (charArray[i] == ' ')
        continue;
            
    // check all remaining characters
    for (int j = i   1; j < charArray.length; j  )
    {
        if (charArray[i] == charArray[j])
        {
            charArray[j] = ' ';
        }
    }
}
        
System.out.println(charArray);

Output:

abcd   e

CodePudding user response:

To put it simply, this is what your code currently does:
For each character in the char array, if the same character appears somewhere in the array starting from the index 1, then change it to a space. This concretely means that all the characters starting from index 1 will be replaced (because the condition that they appear after index 0 will always be satisfied).

A simple example can illustrate why this won't actually work. Suppose your input array is ['h','e','l','l','o'].

When i = 1 and j = 1, charArray[i] == charArray[j] will return true, thus your 'e' will be replaced by a space.

I would suggest looping through the array once, using a data structure that memorizes which characters previously appeared, which in this case corresponds to a Set.

Set<Character> charSet = new HashSet<>();
for (int i = 0; i < charArray.length; i   ) {
  if (charSet.contains(charArray[i])) charArray[i] = ' ';
  else charSet.add(charArray[i]);
}
  • Related