How to count non-space characters in C++ and to split a string into multiple stings on the space. split a?

Does anyone know how to count the non-space characters in a C++ string? Also, does anyone know how to make a C++ function that will split my string into multiple strings based off of the space character and remove the space when splitting?
For example, I would want to split the string "My name is Boris" into...
"My"
"name"
"is"
"Boris" (note the removal of the space after the word)
Does anyone know how to count the non-space characters in a C++ string?

One way would be to iterate through the string and test against std::isalnum().

Also, does anyone know how to make a C++ function that will split my string into multiple strings based off of the space character and remove the space when splitting?

Have you considered a stringstream and then extracting words using the extraction operator?

Does anyone know how to count the non-space characters in a C++ string?

Like so
std::count_if(s.begin(), s.end(), [](char c) { return !std::isspace(c); });

Also, does anyone know how to make a C++ function that will split my string into multiple strings based off of the space character and remove the space when splitting?
Here's one option, although regex_token_iterator is serious overkill for this problem:
1
2
3
4
5
template <typename BidirIt, typename OutputIt>
void split(BidirIt begin, BidirIt end, OutputIt out, std::regex const& re)
{
  std::copy(std::regex_token_iterator(begin, end, re, -1), {}, out);       
}

Call with a std::regex constructed from the string R"(\s+)"
http://coliru.stacked-crooked.com/a/9662a76fa3a7abf9
Last edited on
Thanks!
Topic archived. No new replies allowed.