Calculate Frequency of Characters in a String
Calculate Frequency of Characters in a String
Understanding the frequency of characters in a string is a fundamental concept in text processing and analysis. This problem is common in various applications such as data analysis, cryptography, and natural language processing.
What is Character Frequency?
Character frequency refers to the number of times each character appears in a given string. For example, in the string "hello," the character 'h' appears once, 'e' appears once, 'l' appears twice, and 'o' appears once.
Example:
"hello": {'h': 1, 'e': 1, 'l': 2, 'o': 1}
Solutions:
Now let's see how to calculate the frequency of characters in a string in different programming languages: Java, Python, C, and C++.
1. Java
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class CharacterFrequency {
// Function to calculate the frequency of characters
public static Map<Character, Integer> calculateFrequency(String str) {
Map<Character, Integer> frequencyMap = new HashMap<>();
// Iterate through the string and update the frequency map
for (char ch : str.toCharArray()) {
frequencyMap.put(ch, frequencyMap.getOrDefault(ch, 0) + 1);
}
return frequencyMap;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = scanner.nextLine();
// Calculate and print the frequency of characters
Map<Character, Integer> frequencyMap = calculateFrequency(str);
for (Map.Entry<Character, Integer> entry : frequencyMap.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
scanner.close();
}
}
2. Python
# Function to calculate the frequency of characters
def calculate_frequency(string):
frequency = {}
# Iterate through the string and update the frequency dictionary
for char in string:
if char in frequency:
frequency[char] += 1
else:
frequency[char] = 1
return frequency
# Input from user
string = input("Enter a string: ")
# Calculate and print the frequency of characters
frequency = calculate_frequency(string)
for char, freq in frequency.items():
print(f"{char}: {freq}")
3. C++
#include <iostream>
#include <map>
using namespace std;
// Function to calculate the frequency of characters
map<char, int> calculateFrequency(const string &str) {
map<char, int> frequencyMap;
// Iterate through the string and update the frequency map
for (char ch : str) {
frequencyMap[ch]++;
}
return frequencyMap;
}
int main() {
string str;
cout << "Enter a string: ";
getline(cin, str);
// Calculate and print the frequency of characters
map<char, int> frequencyMap = calculateFrequency(str);
for (const auto &entry : frequencyMap) {
cout << entry.first << ": " << entry.second << endl;
}
return 0;
}
4. C
#include <stdio.h>
#include <string.h>
#define MAX_CHAR 256
// Function to calculate the frequency of characters
void calculateFrequency(char *str, int *frequency) {
// Initialize the frequency array
for (int i = 0; i < MAX_CHAR; i++) {
frequency[i] = 0;
}
// Iterate through the string and update the frequency array
for (int i = 0; str[i] != '\0'; i++) {
frequency[(unsigned char)str[i]]++;
}
}
int main() {
char str[100];
int frequency[MAX_CHAR];
printf("Enter a string: ");
gets(str);
// Calculate the frequency of characters
calculateFrequency(str, frequency);
// Print the frequency of characters
for (int i = 0; i < MAX_CHAR; i++) {
if (frequency[i] > 0) {
printf("%c: %d\n", i, frequency[i]);
}
}
return 0;
}
Explanation of Code:
Each code version defines a function to calculate the frequency of characters in a string.
Java: Uses a
HashMap
to store character frequencies. Iterates through the string, updating the map with each character's count.Python: Utilizes a dictionary to keep track of character frequencies. Iterates through the string, updating the dictionary accordingly.
C++: Employs a
map
to store character frequencies. Iterates through the string, updating the map with each character's count.C: Uses an array to count the frequency of each character (assuming ASCII characters). Iterates through the string, updating the array based on character occurrences.
Sample Input & Output:
Input:
string = "hello"
Output:
h: 1
e: 1
l: 2
o: 1
Conclusion:
Calculating the frequency of characters in a string is a fundamental task in text processing. Understanding how to implement this in various programming languages enhances your skills in data structures and string manipulation.
** Please do subscribe my blog for future updates and share with your friends, if you find this informative **
Comments
Post a Comment