简体   繁体   中英

Splitting a string that has delimiters into 3 variables

I created this code to split a string into 3 different strings str_days, str_column and str_time. I was wondering if there was a better way to split it into 3 variables. Possibly using just 1 if statement?

string::size_type pos = combinedString.find(';');
if (combinedString.npos != pos) {
    combined2 = combinedString.substr(pos + 1);
    str_days = combinedString.substr(0, pos);
}
string::size_type pos2 = combined2.find(';');
if (combined2.npos != pos2) {
    str_column = combined2.substr(pos2 + 1);
    str_time = combined2.substr(0, pos2);
}

If it suits you, you can wrap the gory details behind a variadic function:

#include <string>
#include <algorithm>

template <typename Iterator, typename Delimiter>
bool split_into(Iterator begin, Iterator end, Delimiter, std::string & first)
{
    first.assign(begin, end);
    return true;
}

template <typename Iterator, typename Delimiter, typename... Strings>
bool split_into(Iterator begin, Iterator end, Delimiter d, std::string & first, Strings & ... strings)
{
    auto i = std::find(begin, end, d);

    first.assign(begin, i);

    if (i != end) {
        return split_into(++i, end, d, strings...);
    }

    return sizeof...(Strings) == 0;
}

Then invoke like so:

std::string combinedString("foo;bar;baz;widget");
std::string a, b, c;

split_into(combinedString.begin(), combinedString.end(), ';', a, b, c);

// a == "foo"
// b == "bar"
// c == "baz;widget"

split_into() will return false if there were not enough delimiters encountered to populate all of the passed arguments.

Live demo

You can use std::istringstream with std::getline() , specifying ';' as the line delimiter, eg:

#include <string>
#include <sstream>

std::string combinedString = ...;
std::string str_days, str_time, str_column;

std::istringstream iss(combinedString);
std::getline(iss, str_days, ';');
std::getline(iss, str_time, ';');
std::getline(iss, str_column);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM