将std :: string拆分为向量的正确方法< string> [英] Right way to split an std::string into a vector<string>
本文介绍了将std :: string拆分为向量的正确方法< string>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能重复:
如何拆分字符串?
将字符串拆分为字符串向量的方法。分隔符是空格或逗号。
What is the right way to split a string into a vector of strings. Delimiter is space or comma.
推荐答案
对于空格分隔的字符串,可以这样做:
For space separated strings, then you can do this:
std::string s = "What is the right way to split a string into a vector of strings";
std::stringstream ss(s);
std::istream_iterator<std::string> begin(ss);
std::istream_iterator<std::string> end;
std::vector<std::string> vstrings(begin, end);
std::copy(vstrings.begin(), vstrings.end(), std::ostream_iterator<std::string>(std::cout, "\n"));
输出:
What
is
the
right
way
to
split
a
string
into
a
vector
of
strings
在线演示: http://ideone.com/d8E2G
struct tokens: std::ctype<char>
{
tokens(): std::ctype<char>(get_table()) {}
static std::ctype_base::mask const* get_table()
{
typedef std::ctype<char> cctype;
static const cctype::mask *const_rc= cctype::classic_table();
static cctype::mask rc[cctype::table_size];
std::memcpy(rc, const_rc, cctype::table_size * sizeof(cctype::mask));
rc[','] = std::ctype_base::space;
rc[' '] = std::ctype_base::space;
return &rc[0];
}
};
std::string s = "right way, wrong way, correct way";
std::stringstream ss(s);
ss.imbue(std::locale(std::locale(), new tokens()));
std::istream_iterator<std::string> begin(ss);
std::istream_iterator<std::string> end;
std::vector<std::string> vstrings(begin, end);
std::copy(vstrings.begin(), vstrings.end(), std::ostream_iterator<std::string>(std::cout, "\n"));
输出:
right
way
wrong
way
correct
way
在线演示: http://ideone.com/aKL0m
这篇关于将std :: string拆分为向量的正确方法< string>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文