MMM MMM - 23 days ago 5
C++ Question

Splitting a string withisalnum and store into a vector of strings

I'm working with a string and trying to break it up whenever it is non-alphanumeric (not a-z, A-Z, and 0-9). I found isalnum to be a useful function to use.

For example, if I have the string "bob-michael !#mi%@pa hi3llary-tru1mp"

The vector should contain: bob, michael, mi, pa, hi3llary, and tru1mp.

My current code is:

vector<string> result;
string something = "bob-michael !#mi%@pa hi3llary-tru1mp";
stringstream pie(something);
//not sure what to do after this point(I know, not a lot. See below for my current thinking)


My idea was using a loop and while isalnum results in 1 continue forward, if isalnum results in 0 then push whatever I have so far into the vector of strings. Perhaps I could use isalnum as a delim? I'm having a hard time taking my idea and writing this. Could anyone point me in the right direction? Thanks!

Edit: Thanks everyone for the help.

Answer

The std::replace_if trick I commented on turned out to not be quite as trivial as I thought it was because std::isalnum doesn't return bool.

#include <iostream>
#include <vector>
#include <string>
#include <cctype>
#include <algorithm>
#include <sstream>
#include <iterator>

int main()
{
    std::vector<std::string> result;
    std::string something = "bob-michael !#mi%@pa hi3llary-tru1mp";
    // I expected replace_if(something.begin(), something.end(), &isalnum, " ");
    // would work, but then I did a bit of reading and found is alnum returned int,
    // not bool. resolving this by wrapping isalnum in a lambda
    std::replace_if(something.begin(),
                    something.end(),
                    [](char val)->bool {
                          return std::isalnum(val) == 0;
                     },
                     ' ');
    std::stringstream pie(something);

    // read stream into vector
    std::copy(std::istream_iterator<std::string>(pie),
              std::istream_iterator<std::string>(),
              std::back_inserter<std::vector<std::string>>(result));

    // prove it works
    for(const std::string & str: result)
    {
        std::cout << str << std::endl;
    }
}
Comments