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
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:
- How to split a string in C++?Best solution by Stack Overflow
- How can I echo characters before and after a string?Best solution by stackoverflow.com
- How to marshall a string in C?Best solution by Stack Overflow
- How can I convert a string number to a number in Perl?Best solution by Stack Overflow
- how to extract characters of a language?Best solution by Stack Overflow
Just Added Q & A:
- How many active mobile subscribers are there in China?Best solution by Quora
- How to find the right vacation?Best solution by bookit.com
- How To Make Your Own Primer?Best solution by thekrazycouponlady.com
- How do you get the domain & range?Best solution by ChaCha
- How do you open pop up blockers?Best solution by Yahoo! Answers
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.