Home » Java programs » Java String programs

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

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





Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.



Comments and Discussions


We are using Google to publish ads on our website; Google has its own privacy policies. They may save log, cookies on your system. Google may also collect information of your system like IP address, region, city, country. For more details please go through the Google’s privacy policy.