I need som help with counting words in a string s. count the number of words in a string s. Words are separated by whitespace. Has a sol
istringstream iss(s);
st
You can use getline with character delimiter.
istream& std::getline (istream& is, string& str, char delim);
Something like:
std::replace_if(s.begin(), s.end(), isColon, ';');
istringstream iss(s);
string temp;
int words = 0;
while (std::getline(iss,temp,';') {
++words;
}
And the predicate:
bool isColon (char c) { return (c == ';'); }
Some simple hand crafted loops:
#include <cctype>
#include <iostream>
int main() {
unsigned result = 0;
std::string s = "Hello world";
std::string::const_iterator c = s.begin();
while(c != s.end() && std::isspace(*c)) ++c;
while(c != s.end() && ! std::isspace(*c)) {
++result;
while(++c != s.end() && ! std::isspace(*c));
if(c != s.end()) {
while(std::isspace(*c)) ++c;
}
}
std::cout << "Words in '" << s << "': " << result << '\n';
}
It is also possible to use regular expressions:
std::regex rx("(\\w+)(;|,)*");
std::string text = "this;is,a;test";
auto words_begin = std::sregex_iterator(text.begin(), text.end(), rx);
auto words_end = std::sregex_iterator();
auto count = std::distance(words_begin, words_end);
std::cout << "count: " << count << std::endl;
for(auto i = words_begin; i != words_end; ++i)
{
auto match = *i;
std::cout << match[1] << '\n';
}
The output is:
count: 4
this
is
a
test