Program to Count no of occurrences of a Character in a String | program to print no. of occurrences of a given character in a string

//Program to Count no of Occurrences of a Character in a String 


#include <bits/stdc++.h>
using namespace std;


int main() {
    cout<<"Enter a String: ";                              //requesting a string
    string s;
    getline(cin,s);
                     //to read space separated input
    
    cout<<"\nEnter a character: ";
    char c;
    cin>>c;

    
    int count=0;                         //setting count to 0 
    
    for(int i=0;i<s.length();i++){        //loop to count words
        if(s[i]==c){
            count++;
        }
    }

    
    cout<<"\nNo of occurences of "<<c<<" is: "<<count<<endl;     //printing the required output
    
    return 0;
}

Post a Comment

0 Comments