ADVERTISEMENT
ADVERTISEMENT

Java program to find occurrences of each character in a string

In this java program, we are going to learn how to find occurrences of each character in string? Here, we will read a string and print the total number of count of each character.
Submitted by IncludeHelp, on November 01, 2017

Given a string and we have to find occurrences of each character using java program.

Example:

Input: Save water save earth
Output:
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

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);
  }
}
ADVERTISEMENT

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

Java String Programs »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.