javacodex.com
Java Examples
Java Examples
memu home questions

Count Unique Characters In A String

Here is a java example that utilizes a TreeSet to aide in counting the number of unique characters in a string.

Source: (CountCharacters.java)

import java.util.TreeSet;
 
public class CountCharacters {
 
   public static void main(String args[]){
 
      String str="abcdefaaabbbcccdddeeefff";
      TreeSet<Character> ts = new TreeSet<Character>();
 
      for (int i = 0; i < str.length(); i++) {
         ts.add(new Character(str.charAt(i)));
      }
 
      System.out.println("Unique characters: " + ts);
      System.out.println("Character count: " + ts.size());
 
   }
}
 

Output:

$ java CountCharacters
Unique characters: [a, b, c, d, e, f]
Character count: 6

Contact: javacodex@yahoo.com