How do I ignore spaces when counting characters?
Mar 1, 2016 at 1:10am UTC
Write your question here.
I'm writing a program to count the characters of the last word in a string of input, but excluding the spaces. I've written a program that can count characters, but now I need help ignoring the spaces when counting the characters.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
#include <iostream>
#include <string>
using namespace std;
class CIS14 {
public :
int countLastWordLength(const string str);
};
int main()
{
string mystring;
cout << "type in the word to count" ;
cout << endl;
getline(cin, mystring);
cout << mystring << " - " ;
cout << mystring.length();
cout << " characters" ;
cout << endl;
return 0;
}
Mar 1, 2016 at 1:44am UTC
1 2 3 4 5 6
getline(cin, mystring);
cout << mystring << " - " ;
std::string t = mystring;
t.erase(std::remove_if(t.begin(), t.end(), isspace), t.end());
cout << t.length();
cout << " characters" ;
Or even better
std::count_if(mystring.begin(), mystring.end(), [](char c) {return !isspace(c); })
Last edited on Mar 1, 2016 at 1:48am UTC
Topic archived. No new replies allowed.