Spliiting a string at a delimiter and saving to a variable

The code below splits a string at the delimiter and then prints each string out, so it ends up looking like the following:
scott
tiger
mushroom

I would like to understand how to go about assigning each split section into different variables. For example (split1 = scott, split2 = tiger, etc.). I have seen some ways to do this using streams, but that seems to use spaces unless I am not understanding that right. I took a shot at using arrays but not sure if that is the best option here. Any help would be appreciated.

1
2
3
4
5
6
7
8
9
10
11
 std::string s = "scott>=tiger>=mushroom";
std::string delimiter = ">=";

size_t pos = 0;
std::string token;
while ((pos = s.find(delimiter)) != std::string::npos) {
    token = s.substr(0, pos);
    std::cout << token << std::endl;
    s.erase(0, pos + delimiter.length());
}
std::cout << s << std::endl;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// http://ideone.com/Fe8QHo
#include <iostream>
#include <iterator>
#include <string>
#include <vector>

std::vector<std::string> split(const std::string& s, const std::string& delim)
{
    std::vector<std::string> result;

    std::size_t beg = 0;
    std::size_t end;
    while ((end = s.find(delim, beg)) != std::string::npos)
    {
        result.emplace_back(s.substr(beg, end - beg));
        beg = end + delim.size();
    }

    if (beg)
        result.emplace_back(s.substr(beg));

    return result;
}

template <typename container_type>
void print(std::ostream& os, const container_type& container, const std::string& sep = ", ")
{
    for (std::size_t i = 0; i < container.size() - 1; ++i)
        os << container[i] << sep;

    if (!container.empty())
        os << container.back();
}

int main()
{
    std::string s = "scott>=tiger>=mushroom";
    std::string d = ">=";

    std::cout << '"' << s << "\" split on \"" << d << "\" yields:\n";
    print(std::cout, split(s,d));
}
Using the standard regular expression library:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <string>
#include <vector>
#include <regex>

int main()
{
    const std::string text = "scott>=tiger>=mushroom";
    const std::regex delimiter( ">=" ) ;

    // http://en.cppreference.com/w/cpp/regex/regex_token_iterator
    // note the special value of -1 for the submatch - we want the non-matched sequences of characters
    // ie. iterate over the substrings that are not equal to the delimiter
    const std::vector<std::string> tokens( std::sregex_token_iterator( text.begin(), text.end(), delimiter, -1 ),
                                           std::sregex_token_iterator{} ) ;

    for( const auto& tok : tokens ) std::cout << tok << '\n' ;
}

http://coliru.stacked-crooked.com/a/84a627ea79f8afea
Topic archived. No new replies allowed.