Welcome to ICSE Java Answers. Ask any questions you have related to Java and we will answer them.
Java is a registered trademark of Oracle. This site is in no way related to or endorsed by Oracle.

Input a String in upper case and print the frequency of each character

+1 vote
asked by anonymous

2 Answers

0 votes

We assume that the String contains only uppercase letters and doesn’t contain any other characters like numbers, spaces etc.

We have an array named frequency of length 26. At frequency[0], we store the frequency of the letter ‘A’, at frequency[1], we store the frequency of ‘B’ and so on. The ASCII code of ‘A’ is 65, of ‘B’ is 6 and so on. So, the frequency of some letter will be stored at the position ‘letter-65’.

We take the input String using Scanner and store it in input. An int array frequency of size 26 is created.

We iterate through each character of the String using a for loop. The variable ch stores the character at I and index stores the index that should be incremented. If ch is ‘A’, then ch-65 will  be 65-65 = 0. So, frequency[0]  will be incremented.

Finally, we print the frequencies of the different letters using a for loop. 

Here is the program.

import java.util.Scanner;

public class Frequency {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a String: ");
        String input = scanner.next();
        int[] frequency = new int[26];
        for (int i = 0; i < input.length(); i++) {
            char ch = input.charAt(i);
            int index = ch - 65;
            frequency[index]++;
        }
        System.out.println("Character - Frequency");
        for (int i = 0; i < 26; i++) {
            System.out.println((char) (i + 65) + " " + frequency[i]);
        }
    }
}

Here is a sample output.

Enter a String: SAMPLESTRING
Character - Frequency
A 1
B 0
C 0
D 0
E 1
F 0
G 1
H 0
I 1
J 0
K 0
L 1
M 1
N 1
O 0
P 1
Q 0
R 1
S 2
T 1
U 0
V 0
W 0
X 0
Y 0
Z 0

 

answered by Ranjith (2,408 points)
Frequency of Letters
Very nice logic. Easy to understand
0 votes

	
import java.util.Scanner;

public class CharFrequency
{
	public static void main(String args[])
	{
		Scanner sc = new Scanner(System.in);
		System.out.print(" Enter String: ");
		String str = sc.next();
		char chr[] = str.toCharArray();
		
		int i, j, count, len;
		char ch = ' ';
		
		
		len = chr.length;
		for(i = 0; i < len; i++)
		{
			count = 0;
			ch = chr[i];
			for(j = 0; j < len; j++)
			{
				if(i < j && ch == chr[j])
					break;
				if(ch == chr[j])
					count++;
				if(j == len - 1) 
					System.out.printf(" %c --> %d Times\n", ch, count);
			}
			
		}	
	}
}

 

 

answered by Gautam
it is an awesome program. m happy to get the answer.
...