Calculate the occurrence of specific character in given string in C++

This C++ program is able to calculate the occurrence of a character in a given string. The program involves the application of character array and loop statements. The logic is useful in many areas and applicable in other programming languages too.

How to calculate the occurrence of specific character in given string in C++

Problem statement

User enters a string of any length and a character value. Then find the occurrence of that character in the string.

  • String length can be as per the user data.

Methodology

  • Declare a character array (string) of sufficient length.
  • Take the input for that string.
  • Take the character input whose occurrence is required to be measured.
  • Calculate the occurrence and print on the screen.

Program

Following is the complete program to calculate and print the occurrence in a given string.

/* C++ program to calculate occurrence of a character in given string**
 ** enter string value of your choice**
 ***enter different string values for different results***
 note: enter the string only in upper case or lower case but not both, otherwise the result may be inaccurate....
 */

#include <iostream>
#include<string.h>

using namespace std;

int main()
{
    char string[80], ch;
    cout<<"Enter string: ";                 // string value
    cin.getline(string,80);

    cout<<"Enter character whose occurrence is required ";
    cin>>ch;

    int count=0;
    for(int i=0;i<strlen(string);i++){
        if(string[i]==ch)                     // logic for comparison
            count++;                            // increment
    }

    cout<<"Total occurrence of "<<ch<<" is "<<count<<" times."<<endl;
    return 0;
}

Example output

Enter string: this is new delhi.
Enter character whose occurrence is required s
Total occurrence of s is 2 times.

Process returned 0 (0x0) execution time : 19.246 s
Press any key to continue.
Enter string: this is a sample sring for the program
Enter character whose occurrence is required i
Total occurrence of i is 3 times.

Process returned 0 (0x0) execution time : 21.279 s
Press any key to continue.

Program explanation

  1. Initialize a string of length 80.
  2. Take the string input value from the user.
  3. Take character input whose occurrence is required.
  4. Declare a variable count to store the result.
  5. Use for loop so that it can traverse through the entire string.
  6. Use if statement for comparison.
  7. Increment the count variable on each success condition.
  8. Print the result on the screen.

Also, read

Leave a Reply

Your email address will not be published. Required fields are marked *