top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to remove repeated characters in a given string without modifying source string in Java?

+1 vote
340 views

How to remove specified strings in given string without modifying source string
Ex:
Source String="doubbllee"
Output Required="double".

posted Mar 17, 2014 by Ashwini Miraj

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

This should work, source: http://stackoverflow.com/questions/2598129/function-to-remove-duplicate-characters-in-a-string

public static void removeDuplicates(char[] str) {

  if (str == null) return; // if the array does not exist..nothing to do return.
  int len = str.length; // get the array length.
  if (len < 2) return; // if its less than 2..can't have duplicates..return.

  int tail = 1; // number of unique char in the array.

  // start at 2nd char and go till the end of the array.
  for (int i = 1; i < len; ++i) { 
    int j;

    // for every char in outer loop check if that char is already seen.
    // char in [0,tail) are all unique.
    for (j = 0; j < tail; ++j) {
      if (str[i] == str[j]) break; // break if we find duplicate.
    }

    // if j reachs tail..we did not break, which implies this char at pos i
    // is not a duplicate. So we need to add it our "unique char list"
    // we add it to the end, that is at pos tail.
    if (j == tail) {
      str[tail] = str[i]; // add
      ++tail; // increment tail...[0,tail) is still "unique char list"
    }
  }

  str[tail] = 0; // add a 0 at the end to mark the end of the unique char.
}
answer Mar 17, 2014 by Salil Agrawal
Similar Questions
+2 votes

Remove duplicate characters from given string?

Input: "cutcopypaste"
Output: "uoyase"

0 votes

Given a sentence and a word, remove all occurrences of the word in the sentence.

For example, removing “is” from the sentence “This is a boy.” becomes “Th a boy.”

–1 vote

Write a C program to check if the given string is repeated substring or not.
ex
1: abcabcabc - yes (as abc is repeated.)
2: abcdabababababab - no

...