Java program to find the frequency of character in a string
Here's a Java program to find the frequency of each character in a string:
import java.util.HashMap; import java.util.Scanner; public class CharacterFrequency { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a string: "); String input = scanner.nextLine(); scanner.close(); HashMap<Character, Integer> frequencyMap = new HashMap<>(); for (int i = 0; i < input.length(); i++) { char ch = input.charAt(i); if (frequencyMap.containsKey(ch)) { frequencyMap.put(ch, frequencyMap.get(ch) + 1); } else { frequencyMap.put(ch, 1); } } System.out.println("Character frequencies:"); for (char ch : frequencyMap.keySet()) { int frequency = frequencyMap.get(ch); System.out.println(ch + ": " + frequency); } } }
In this program, we first prompt the user to enter a string using the Scanner
class.
We then create a HashMap
called frequencyMap
to store the frequency of each character in the string. We use a for
loop to iterate over each character in the string. For each character, we check if it is already present in the frequencyMap
. If it is, we increment its frequency by 1. If it is not, we add it to the frequencyMap
with a frequency of 1.
Finally, we iterate over the frequencyMap
and print the frequency of each character in the string.
The output of this program will be something like:
Enter a string: hello Character frequencies: e: 1 h: 1 l: 2 o: 1
This shows that the character 'e' appears once, the characters 'h' and 'o' each appear once, and the character 'l' appears twice in the string "hello".