How to Count Characters in a String in C++

This is the simple and logic building C++ programming exercise. The program will count the number of characters in string in C++ program. The program will display each character along with its occurrence in the string.  

Source Code 

#include <iostream>
#include "fromMain.cpp"
using namespace std;
int main(int argc, char** argv) {
string sentence;
int count=0;
int a;
char c1;
fromMain obj_m;

cout<< "Enter a sentence with \".\" at End"<<endl;
getline(cin,sentence,'.') ;

for(int i=65;i<123;i++){
if(((i>64)&&(i<91))||((i>96)&&(i<123))){
if(i==97){
cout<<endl;
}
cout<< (char)i<< " = ";
for(int j=0;j<sentence.length();j++){
a=sentence[j];
if(a==i){
count=count+1;
}
}
cout<<count<< " | ";
}
count=0;
}
return 0;
}

Output of the Program

 Count Characters in a String in C++

Share on Google Plus

About Asad

Asad Niazi is Software Engineer , Programmer, Web Developer and a young mentor of BloggersTown and PProgramming. Asad Love to writes about Technology, Programming, Blogging and make money online.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment