[英]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. 我创建了此代码,将一个字符串分成3个不同的字符串str_days,str_column和str_time。 I was wondering if there was a better way to split it into 3 variables. 我想知道是否有更好的方法将其分为3个变量。 Possibly using just 1 if statement? 可能只使用1个if语句?
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. 如果遇到的分隔符不足以填充所有传递的参数,则split_into()
将返回false。
You can use std::istringstream
with std::getline()
, specifying ';'
您可以将std::istringstream
与std::getline()
,并指定';'
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.