Senin, 18 Oktober 2010

String Split with Some Delimiters and Remove Duplicate

in this tutorial, I Want To show how to split a String into tokens with some delimiters and remove duplicate. thus, the result is a unique tokens. I am using Java. 
For example: 
String input = "AAAA AAAA BBBB BBBB CCCC djgu";
the result should be: {AAAA, BBBB, digu, CCCC}
 

The following is the complete source code:
     
String s2 = "cahdt aaaa aaaa bbbbb ddddd";

        
List li = new ArrayList ();
        
StringTokenizer st = new StringTokenizer (s2 ,";&@! - ");

        
while (st.hasMoreTokens ()) {
            
String temp = st.nextToken ();
            
li.add (temp);
        
}

         
Set set2 = new HashSet <string> <string> (li);
         
String [] result2 = new String [set2.size ()];
         
set2.toArray (result2);
         
for (String s: result2) {
            
System.out.print (s + ",");
         
}

Tidak ada komentar:

Posting Komentar