Program to check : Frequency of Character in a String
Definition & Explanation
The task is to calculate the frequency of each character in a given string. This means counting how many times each character appears in the string and storing this information for each unique character.
More Description
Program Logic
What we want from the code:
- Input: Accept a string as input.
- Count Frequency: Count the frequency of each character in the string.
- Output: Print or store the frequency of each character.
Program Logic:
- Input String: Accept a string from the user or use a predefined string.
- Initialize Frequency Count: Initialize a data structure (e.g., array, map, dictionary) to store the frequency count of characters.
- Count Frequency: Iterate through each character of the string and update the frequency count accordingly.
- Output Frequency: Print or store the frequency of each character.
C
Method 1 :
#include <stdio.h>
#define MAX_CHARS 256
void countFrequency(char *str) {
int freqMap[MAX_CHARS] = {0};
// Count frequency of characters
for (int i = 0; str[i]; i++)
freqMap[str[i]]++;
// Output frequency of characters
for (int i = 0; i < MAX_CHARS; i++) {
if (freqMap[i] != 0)
printf("Character: %c, Frequency: %d\n", i, freqMap[i]);
}
}
int main() {
char str[] = "hello";
countFrequency(str);
return 0;
}
Output :
C++
Method 1 :
#include <iostream>
#include <unordered_map>
using namespace std;
void countFrequency(string str) {
unordered_map<char, int> freqMap;
// Count frequency of characters
for (char ch : str)
freqMap[ch]++;
// Output frequency of characters
for (auto entry : freqMap)
cout << "Character: " << entry.first << ", Frequency: " << entry.second << endl;
}
int main() {
string str = "hello";
countFrequency(str);
return 0;
}
Output :
JAVA
Method 1 :
import java.util.HashMap;
import java.util.Map;
public class FrequencyCount {
public static void countFrequency(String str) {
Map<Character, Integer> freqMap = new HashMap<>();
// Count frequency of characters
for (char ch : str.toCharArray())
freqMap.put(ch, freqMap.getOrDefault(ch, 0) + 1);
// Output frequency of characters
for (Map.Entry<Character, Integer> entry : freqMap.entrySet())
System.out.println("Character: " + entry.getKey() + ", Frequency: " + entry.getValue());
}
public static void main(String[] args) {
String str = "hello";
countFrequency(str);
}
}
Output :
Python
Method 1 :
from collections import Counter
def count_frequency(input_string):
frequency = Counter(input_string)
for char, freq in frequency.items():
print(f"Character: {char}, Frequency: {freq}")
# Test the function
input_string = "hello"
count_frequency(input_string)
Output :
Character: h, Frequency: 1
Character: e, Frequency: 1
Character: l, Frequency: 2
Character: o, Frequency: 1