# Program to find the frequency of characters in a string | faceprep

Program to find the frequency of characters in a string is discussed here. Given a string, the frequency of occurrence of each character is displayed as output.

Input Format:
Input consists of 1 string.

Sample Input & Output:

Output:
e 1
g 2
l 1
o 2

## Algorithm to find the frequency of characters in a string

• Input the string from the user.
• Traverse the string, character by character and store the count of each of the characters in an array.
• Print the array that contains the frequency of all the characters.

Program to find the frequency of characters in a string is given below.

/* C Program to Find the Frequency of Characters in a String */

#include <stdio.h>
#include <string.h>

int main()
{
char str[100];
int i;

int freq[256] = {0};
gets(str);

for(i = 0; str[i] != ‘\0’; i++)
{
freq[str[i]]++;
}

for(i = 0; i < 256; i++)
{
if(freq[i] != 0)
{
printf(“%c %d\n”, i, freq[i]);
}
}

return 0;
}

/* C++ Program to Find the Frequency of Characters in a String */

#include <bits/stdc++.h>
using namespace std;
int main()
{
char str[100];
int i;

int freq[256] = {0};
cin >> str;

for(i = 0; str[i] != ‘\0’; i++)
{
freq[str[i]]++;
}

for(i = 0; i < 256; i++)
{
if(freq[i] != 0)
{
cout << (char)i << ” ” << freq[i] << endl;
}
}

return 0;
}

/* Java program to find the frequency of characters in a string */
import java.util.*;

public class Main
{

static final int SIZE = 26;

static void freq_of_chars(String str)
{
int n = str.length();

int[] freq = new int[SIZE];

for (int i = 0; i < n; i++)
freq[str.charAt(i) – ‘a’]++;

for (int i = 0; i < n; i++) {

if (freq[str.charAt(i) – ‘a’] != 0) {

System.out.print(str.charAt(i));
System.out.println(freq[str.charAt(i) – ‘a’] + ” “);

freq[str.charAt(i) – ‘a’] = 0;
}
}
}

public static void main(String args[])
{
String str;
Scanner sc = new Scanner(System.in);
str = sc.nextLine();
freq_of_chars(str);
}
}

# Python program to find the frequency of characters in a string
import numpy as np
def freq_of_chars(str) :

n = len(str)

freq = np.zeros(26, dtype = np.int)

for i in range(0, n) :
freq[ord(str[i]) – ord(‘a’)] += 1

for i in range(0, n) :

if (freq[ord(str[i])- ord(‘a’)] != 0) :

print (str[i], freq[ord(str[i]) – ord(‘a’)],
end = ” \n”)

freq[ord(str[i]) – ord(‘a’)] = 0

str = input(“Enter the string : “)
freq_of_chars(str)

Output: