Q:

Java program to find occurrences of each character in a string

belongs to collection: Java String Programs

0

Java program to find occurrences of each character in a string

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program

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

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java String Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to reverse words of a string... >>
<< Java program to separate all tokens (words) using ...