Java Data Type How to - Find duplicate characters in a String and count the number of occurances








Question

We would like to know how to find duplicate characters in a String and count the number of occurances.

Answer

// w ww. j  a v  a2  s.  c  o m
public class Main {
  public static void main(String[] args) throws Exception {
    String ch = "this is a test this is a test test is is is a a a a a a a";
    int count = 0, len = 0;
    do {
      try {
        char name[] = ch.toCharArray();
        len = name.length;
        count = 0;
        for (int j = 0; j < len; j++) {
          if ((name[0] == name[j])
              && ((name[0] >= 65 && name[0] <= 91) || (name[0] >= 97 && name[0] <= 123)))
            count++;
        }
        if (count != 0)
          System.out.println(name[0] + " " + count + " Times");
        ch = ch.replace("" + name[0], "");
      } catch (Exception ex) {
      }
    } while (len != 1);
  }
}