Java Program to Find Occurrences of Each Character in a String

You are currently viewing Java Program to Find Occurrences of Each Character in a String

Java program to find occurrences of each character in a string

import java.io.*;
import java.util.Scanner;

public class FindDuplicateChar {
  public static void main(String[] args) throws IOException {
    // create object of the string.
    String S;
    Scanner scan = new Scanner(System.in);

    // enter your statement here.
    System.out.print("Enter the Statement : ");

    // will read statement and store it in "S" for further process.
    S = scan.nextLine();
    int count = 0, len = 0;
    do {
      try {
        // this loop will identify character and find how many times it occurs.
        char name[] = S.toCharArray();
        len = name.length;
        count = 0;
        for (int j = 0; j < len; j++) {
          // use ASCII codes for searching.
          if ((name[0] == name[j]) && ((name[0] >= 65 && name[0] <= 91) || (name[0] >= 97 && name[0] <= 123)))
            count++;
        }
        if (count != 0) {
          // print all the repeated characters.
          System.out.println(name[0] + " " + count + " Times");
        }
        S = S.replace("" + name[0], "");
      } catch (Exception e) {
        System.out.println(e);
      }
    }
    while (len != 1);
  }
}

Output

First run:
Enter the Statement : Save water save earth
S 1 Times
a 4 Times
v 2 Times
e 4 Times
w 1 Times
t 2 Times
r 2 Times
s 1 Times
h 1 Times

Second run:
Enter the Statement : I love my india.
I 1 Times
l 1 Times
o 1 Times
v 1 Times
e 1 Times
m 1 Times
y 1 Times
i 2 Times
n 1 Times
d 1 Times
a 1 Times

Ranjith

Hi, I'm Manoj a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Reply