How to count number of occurrences of pattern within a string?

Count number of occurrences of characters in a string C++?

  • I am having problems with a program I am writing in C++. It is suppose to take a user created sentence then out put the number of occurrences for the letters that make up the string. ...show more

  • Answer:

    This is a solution not using map, but an array of integers. It also shows you how remove_if works for you: #include <iostream> #include <algorithm> using namespace std; int main() { int ar[127] = {0}; string userInput; cout << "\nYour input> "; getline(cin, userInput); string::iterator pend = remove_if(userInput.begin(), userInput.end(), [](const char& c){return c==' ' ? true : false;}); userInput.resize( distance( userInput.begin(), pend ) ); for(int i=0; i<userInput.length( ); i++) ar[userInput[i]]++; cout << "Your line of text contains the following characters:" << endl; for(int i = 0; i < 127; i++) { if (ar[i]) cout << (char)i << " " << ar[i] << endl; } return 0; }

WPCQYPUJPI3BT3YUAFTJW424BI at Yahoo! Answers Visit the source

Was this solution helpful to you?

Other answers

post your code?

DFDSFEFD

use a map. A map is a data structure that can associate 2 different values with one another. In this case we will associate each character with it's occurrence count. #include <iostream> #include <map> using namespace std; int main( ) { map<char, int> occurrences; string sentence; cout<<"Enter a sentence: "; getline(cin, sentence); for(int i=0; i<sentence.length( ); i++) { //go through the string occurrences[sentence[ i ] ]++; add one to the count for the character } //go through the map and print the table of occurences map<char, int>::iterator it; for(it = occurrences.begin( ); it!=occurrences.end(); it++) { cout<<it->first <<" : "<<it->second<<endl; } }

Ari

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.