Fx{r} is trying to start the Fx{r} Community! Please join our group on Adobe Groups following this link: http://groups.adobe.com/groups/ab29539ab9.
Fx{r} is now on Twitter too. Follow us @ twitter.com/fx_r!
«
»

ActionScript, How to, Testing

Remove Duplicate Chars from a String

Andrei Ionescu | 11.03.08 | 16 Comments

Table of contents

  1. Remove Duplicate Chars from a String
  2. Comparison: Remove Duplicate Chars from a String Via Array and RegExp
Google Buzz

This post is about how to remove duplicate characters from a string. And what I mean is that I want to make every char unique.

Ex: “aabbbcccaadddee” will become “abcde“.

In “short words” the following steps are taken:

  1. Split the string to an array (source array)
  2. Create a second empty array which will retain the unique values
  3. Sort the source array with case insensitive
  4. Store current value for comparison
  5. Walk through the whole source array and for each character check if is the same with current value variable – if it is that character is not already added we add it to the second array (this because the source array is sorted and there cannot be an array like this after sorting:
    array("a","b","a")

    but only sorted… like this:

    array("a","a","b")
  6. Join back the second array to a string

These are the steps and here is a function in Actionscript 3:

private function removeDuplicates(string:String):String 
{ 
    var arr:Array = string.split('');
    var currentValue:String = ""; 
    var tempArray:Array = new Array(); 
    arr.sort(Array.CASEINSENSITIVE); 
    arr.forEach( 
        function(item:*,index:uint,array:Array):void 
        { 
            if (currentValue != item) 
            { 
                tempArray.push(item); 
                currentValue = item; 
            } 
        } 
    ); 
    return tempArray.sort(Array.CASEINSENSITIVE).join(''); 
}

I tried to have the same result using regular expressions but no success. And I stress that I meant about removing duplicates and making a unique chars string. Removing only duplicates is easy and I can put a regular expression here for that but that is not the purpose of this article.

If anyone resolved this using RegExp please share :) .

Share and Enjoy:
  • Twitter
  • Google Buzz
  • LinkedIn
  • Google Bookmarks
  • del.icio.us
  • Digg
  • Sphinn
  • blogmarks
  • Reddit
  • StumbleUpon
  • Facebook
  • DZone
  • FriendFeed
  • Yahoo! Buzz
  • Yahoo! Bookmarks
  • Slashdot
  • MySpace
  • Add to favorites




Tags: , , ,

This post was written by Andrei Ionescu

Views: 11570

related

16 Comments

have your say

Add your comment below, or trackback from your own site. Subscribe to these comments.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

:

:


«
»