11 Replies Latest reply: Jul 11, 2008 5:36 AM by 634908 RSS

    Method to remove Duplicate char from a StringBuilder

    843785
      hello,

      I'm trying to create a method to remove duplicate char from a Stringbuilder so if I inputted 'ttttttt' I would
      only be returned with 't' my method at the moment is
      public static String Dups(String aString)
      {
      StringBuilder aSB = new StringBuilder(aString);
      
      for (int i = 0;i<aSB.length();i++)
         {
            if(aSB.charAt(i)==aSB.charAt(i++))
            {
            aSB.deleteCharAt(i);
            }
         }
      return aSB.toString();
      }
      The code is remove some 't''s but not all duplicates
      does anyone know where I'm going wrong?

      Thanks
        • 1. Re: Method to remove Duplicate char from a StringBuilder
          843785
          Say you enter 'SSS'

          Your code will see that index 0 and 1 are both S, so it will delete index 1, giving you 'SS'. Now your length is 2 and your loop index is 1, so you start from the second S. Since your loop index is always increasing, you'll never go back and compare your first character again...not to mention you'll likely get out of bounds exceptions as you delete while traversing over the length.
          • 2. Re: Method to remove Duplicate char from a StringBuilder
            843785
            Can you think of a better method to complete the task?
            • 3. Re: Method to remove Duplicate char from a StringBuilder
              843785
              ShockUK wrote:
              Can you think of a better method to complete the task?
              Yes. Start with a new, empty, StringBuilder and copy over characters from the original string only when they are not duplicates.
              • 4. Re: Method to remove Duplicate char from a StringBuilder
                843785
                Oh, I just noticed something else...something pretty important. Do you know what "i++" means? It means that you use the current value of i for whatever operation you're in, and afterwards you increment i by 1. So in this line:
                if(aSB.charAt(i)==aSB.charAt(i++)) {
                    //code
                }
                What you're really saying is:
                if(aSB.charAt(i)==aSB.charAt(i)) { //now i is incremented by 1
                    //code
                }
                Which of course is always true. This is also the reason why you aren't getting the out of bounds exception I would expect. Notice you'll get that exception if you use this:
                if(aSB.charAt(i)==aSB.charAt(i+1))
                To fix this problem you need to limit your loop index to less than length() minus 1:
                for (int i = 0;i<aSB.length() - 1;i++)
                But that still might not give you the results you want.

                Edited by: newark on Jul 8, 2008 4:36 PM
                • 5. Re: Method to remove Duplicate char from a StringBuilder
                  800282
                  String s = "aaaaaabbbbbbbbcccccccccddddddd";
                  System.out.println(s.replaceAll("(.)\\1+", "$1"));
                  • 6. Re: Method to remove Duplicate char from a StringBuilder
                    843785
                    prometheuzz wrote:
                    String s = "aaaaaabbbbbbbbcccccccccddddddd";
                    System.out.println(s.replaceAll("(.)\\1+", "$1"));
                    I knew it was only a matter of time before someone brought out a regex. One of these days I'll learn how to use them...but for now it's all gibberish and/or magic to me.
                    • 7. Re: Method to remove Duplicate char from a StringBuilder
                      843785
                      I'm trying to only copy non-dups to a new StringBuilder and struggling, so I have the following
                      public static String Dup(String aString)
                      {
                      StringBuilder aSB = new StringBuilder(aString);
                      StringBuilder aSB2 = new StringBuilder();
                      for (int i = 0;i<aSB.length();i++)
                         {
                            if(aSB.charAt(i)==aSB.charAt(i++))
                            {
                             
                            }
                            else
                            {
                             aSB2.append(aSB.charAt(i));  
                            }
                         }
                      return aSB2.toString();
                      }
                      Problem I've also got is I don't want to use this lin
                      if(aSB.charAt(i)==aSB.charAt(i++))
                      and trying to use
                      if(aSB.charAt(i).equals(aSB.charAt(i++)))
                      but I get the error "char cannot be dereferenced"

                      Does anyone know were it's falling down or how to fix
                      the problem of only copying non-dups to the new
                      StringBuilder?
                      • 8. Re: Method to remove Duplicate char from a StringBuilder
                        800282
                        newark wrote:
                        ... One of these days I'll learn how to use them...
                        Well, perhaps today is that day:
                        Match:
                        (.)    any character, stored in group 1 (because of the parenthesis)
                        \\1+   matches whatever the first group matched, one or more times
                        
                        Replacement:
                        $1     the first group (in this case, the first character of 2 or 
                               more succeeding characters)
                        • 9. Re: Method to remove Duplicate char from a StringBuilder
                          843785
                          public class StringBuilderExample {
                              public static StringBuilder removeDuplicates(String input) {
                                  StringBuilder sb = new StringBuilder();
                                  for(int i=0; i<input.length(); ++i) {
                                      char ch = input.charAt(i);
                                      if (i==0 || ch != input.charAt(i-1)) {
                                          sb.append(ch);
                                      }
                                  }
                                  return sb;
                              }
                          
                              public static void main(String[] args) {
                                  String s = "pubbliiiic  sstaatiiic void main(String[[[] args) {";
                                  System.out.println(removeDuplicates(s));
                              };
                          }
                          • 10. Re: Method to remove Duplicate char from a StringBuilder
                            843785
                            ShockUK wrote:
                            trying to use
                            if(aSB.charAt(i).equals(aSB.charAt(i++)))
                            but I get the error "char cannot be dereferenced"
                            You can't use the equals() method on a char. A char is a primitive, not a normal object that you can call methods on. Ond difference being that objects have properties, while primitives have values...so to compare primitives you have to use basic equality, like ==, <, >, and !=. Since Strings aren't primitives you can use equals() to compare values, but don't confuse Strings with chars.

                            Also, you're still using "i++". Stop that. The ++ operator increments the value of i, which your loop is supposed to be doing. Having "i++" in two places increments i by two every iteration.
                            • 11. Re: Method to remove Duplicate char from a StringBuilder
                              634908
                              Sample:

                              StringBuilder s=new StringBuilder("qqqdfdfsdfjjjkkqwwqqqq");
                              int i=0;
                              while (i<s.length()-1){
                              if (s.charAt(i)==s.charAt(i+1))
                              s.deleteCharAt(i);
                              else i++;
                              }
                              System.out.println(s);

                              }