Exercise:
Write a C++ program that can determine the frequency of the characters present in a string.
Program 1: String Object
Click Here to View Solution:
#include <iostream>
using namespace std;
int main()
{
string str;
int check = 0;
char find = 'o'; // to find any letter from a-z or A-Z
cout<<"Enter a sentence to check o "<<endl;
getline (cin,str);
for (int x = 0; x < str.size(); x++)
{
if (str[x] == find)
{
++ check;
}
}
cout << "Number of " << find << " = " << check;
return 0;
}
Click Here to View Output:
Enter a sentence to check o code of code Number of o = 3
Click Here to View Explanation:
- This code is used to count the number of repeatedly appearing characters in a string. To begin, the length of a character is stored using the
for
loop. - Through every iteration where the character being checked for is present, the value of
check
is increased by 1. - The iterations continue until the character is found empty (null).
- Through every iteration, it is checked if the character is present.
Program 2: C Style String
Click Here to View the Solution:
#include <iostream>
using namespace std;
int main ( )
{
char c[] = "I learn programming from codeofcode.", check = 'r' ;
int num = 0;
for(int n=0; c[n] != '\0'; ++n)
{
if (check == c[n])
++num;
}
cout << "The frequency of " << check << " in the sentence is: " <<num;
return 0;
}
Click Here to View the Output:
The frequency of r in the sentence is: 4
Click Here to View the Explanation:
- The code is similar to the above one.
- The loops continue until a null character
'\0'
is encountered which marks the ending of a sentence. - The presence of the character is checked after each iteration.