function to remove duplicate characters in a string

Posted by Codenotguru on Stack Overflow See other posts from Stack Overflow or by Codenotguru
Published on 2010-04-08T07:06:55Z Indexed on 2010/04/08 7:13 UTC
Read the original article Hit count: 163

Filed under:

The following code is trying to remove any duplicate characters in a string.Iam not sure if the code is right??Can anybody help me with the working of the code i.e whats actually happening when there is a match in characters?

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;
}

© Stack Overflow or respective owner

Related posts about string