How to count the letters in a String through a Java Program

In this program we shall read a line using the Scanner class and count the number of different characters in the String. To begin with we create a Scanner after importing the java.util.Scanner class.

import java.util.Scanner;
Scanner s=new Scanner(System.in);
String string=s.nextLine();
The nextLine method reads characters till enter is pressed. After this we convert the string to upper case so that we do not have to maintain a count of capital and small letters separately. Finally, we create an array of length 26 to store the number of occurrences.

package strings;

import java.util.Scanner;

public class CountCharacters {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
String string=s.nextLine();
string=string.toUpperCase();
int[] counts=new int[26];
for(int i=0;i<=string.length()-1;i++)
{

char ch=string.charAt(i);
if(!Character.isLetter(ch))
continue;
int pos=ch-'A';
counts[pos]++;

}

for(int i=0;i<=counts.length-1;i++)
{
if(counts[i]<=0)
continue;
char ch=(char)('A' + i);
System.out.println(ch + " = " + counts[i]);
}
}

}

Output

Leave a Reply