Count Frequency of Character in String
“Count Frequency of Character in String” is a basic problem of string data structure. Here, we are given a string of length ‘n’ and our task is to write a program to count how many times a particular character occurs in the string.
Example:
Input: Enter a string: abcdrfedsdfddgr Enter character : d Output: The number of occurrences of d in abcdrfedsdfddgr is 3
The simplest solution of the above problem is to traverse the given string and count each occurrence of the given character in the string.
C++ Program to Count Frequency of Character in String is as follows:
/* Program to Count Frequency of Character in String */
#include<bits/stdc++.h>
#define len 1000
using namespace std;
int main()
{
char str[len];
cout<<"Enter the string:\n";
cin>>str;
char ch;
cout<<"Enter a character:\n";
cin>>ch;
int count = 0;
/* Loop to traverse the string and
count the occurrences of the character
in the string */
for(int i = 0;i < len && str[i]!=' /* Program to Count Frequency of Character in String */ #include<bits/stdc++.h> #define len 1000 using namespace std; int main() { char str[len]; cout<<"Enter the string:\n"; cin>>str; char ch; cout<<"Enter a character:\n"; cin>>ch; int count = 0; /* Loop to traverse the string and count the occurrences of the character in the string */ for(int i = 0;i < len && str[i]!='\0'; i++) { if(str[i] == ch) count++; } cout<<"\nThe number of occurrences of "<<ch<<" in "<<str<<" is "<<count; }
'; i++)
{
if(str[i] == ch)
count++;
}
cout<<"\nThe number of occurrences of "<<ch<<" in "<<str<<" is "<<count;
}
OUTPUT: Enter the string: Helpmestudybro Enter a character: e The number of occurrences of e in Helpmestudybro is 2 Time Complexity: O(n), where n is the length of the string.
Related Posts:
- Program to Count Number of Vowels and Number of Consonants in a String.
- Program to Check if String is alphabetic or numeric or alpha-numeric.
- Program to copy one String to Another.
- Program to Concatenate Two Strings.
- Program to Check whether given String is Palindrome or not.
- Program to convert lower-case alphabet to upper-case alphabet and vice-versa.
- Program to count total number of words in a string.
- Program to find smallest and largest word of the String.
- Program to find Most Frequent Character of the String.
- Program to Remove all the blank spaces from the String.
- Program to check if String is isogram or not.
- Program to Reverse Each word of the String.
- Program to Print All the Substring of the Given String.
- Program to find longest palindromic Substring.
- Program to check Anagram Strings.
- Program to check whether two Strings are Rotation of each other or not.
- Program to check Palindromic Anagram.
- Program to print all the Palindromic Substring of the String.
- Program to check Panagram String.
- Program to find first non-repeating character of the String.