使用C++拆分字符串11
使用C++ 11拆分字符串最简单的方法是什么?使用C++拆分字符串11
我已经看到了这个post使用的方法,但是我觉得应该使用新标准做一个不太冗长的方法。
编辑:我想有一个vector<string>
作为结果,并能够在一个字符上划界。
我不知道这是不是很详细,但它可能更容易为动态语言,如JavaScript的经验丰富的人。它使用的唯一C++ 11功能是lambdas。
#include <algorithm>
#include <string>
#include <cctype>
#include <iostream>
#include <vector>
int main()
{
using namespace std;
string s = "hello how are you won't you tell me your name";
vector<string> tokens;
string token;
for_each(s.begin(), s.end(), [&](char c) {
if (!isspace(c))
token += c;
else
{
if (token.length()) tokens.push_back(token);
token.clear();
}
});
if (token.length()) tokens.push_back(token);
return 0;
}
为什么不'for(auto const c:s){...}'? – 2012-04-19 12:19:07
std::regex_token_iterator
基于正则表达式执行通用标记。它可能会或可能不会矫枉过正对单个字符做简单的拆分,但它的工作原理,是不是太冗长:
std::vector<std::string> split(const string& input, const string& regex) {
// passing -1 as the submatch index parameter performs splitting
std::regex re(regex);
std::sregex_token_iterator
first{input.begin(), input.end(), re, -1},
last;
return {first, last};
}
好主意,超级难读。 – 2012-02-24 21:36:03
应该提到这是MSFT特定的。在POSIX系统上不存在。 – jackyalcine 2014-09-06 20:11:26
看起来它也可用于[boost。](http://www.boost.org/doc/libs/1_56_0/libs/regex/doc/html/boost_regex/ref/regex_token_iterator.html) – phs 2014-09-06 20:57:17
我的选择是boost::tokenizer
,但我没有任何工作任务重和测试与庞大的数据。 来自实例文档提升与拉姆达修改:
#include <iostream>
#include <boost/tokenizer.hpp>
#include <string>
#include <vector>
int main()
{
using namespace std;
using namespace boost;
string s = "This is, a test";
vector<string> v;
tokenizer<> tok(s);
for_each (tok.begin(), tok.end(), [&v](const string & s) { v.push_back(s); });
// result 4 items: 1)This 2)is 3)a 4)test
return 0;
}
为什么不以范围为基础? – 2012-04-19 12:19:46
在C++ 11中,for(auto && s:tok){v.push_back(s); }'。 – 2015-05-26 19:08:03
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
vector<string> split(const string& str, int delimiter(int) = ::isspace){
vector<string> result;
auto e=str.end();
auto i=str.begin();
while(i!=e){
i=find_if_not(i,e, delimiter);
if(i==e) break;
auto j=find_if(i,e, delimiter);
result.push_back(string(i,j));
i=j;
}
return result;
}
int main(){
string line;
getline(cin,line);
vector<string> result = split(line);
for(auto s: result){
cout<<s<<endl;
}
}
这里是一个(也许更简洁)的方式来分割字符串(根据你所提到的post)。
#include <string>
#include <sstream>
#include <vector>
std::vector<std::string> split(const std::string &s, char delim) {
std::stringstream ss(s);
std::string item;
std::vector<std::string> elems;
while (std::getline(ss, item, delim)) {
elems.push_back(item);
// elems.push_back(std::move(item)); // if C++11 (based on comment from @mchiasson)
}
return elems;
}
如果你使用的是C++ 11,你也可以在插入到你的矢量时避免字符串拷贝: elems.push_back(std :: move(item)); – mchiasson 2015-02-15 16:03:07
这是我的答案。详尽,可读和高效。
std::vector<std::string> tokenize(const std::string& s, char c) {
auto end = s.cend();
auto start = end;
std::vector<std::string> v;
for(auto it = s.cbegin(); it != end; ++it) {
if(*it != c) {
if(start == end)
start = it;
continue;
}
if(start != end) {
v.emplace_back(start, it);
start = end;
}
}
if(start != end)
v.emplace_back(start, end);
return v;
}
下面是一个字符串分割和填充用boost
所提取的元件的载体的一个例子。
#include <boost/algorithm/string.hpp>
std::string my_input("A,B,EE");
std::vector<std::string> results;
boost::algorithm::split(results, my_input, is_any_of(","));
assert(results[0] == "A");
assert(results[1] == "B");
assert(results[2] == "EE");
另一个正则表达式的解决方案inspired by other answers但希望更短,更易于阅读:
std::string s{"String to split here, and here, and here,..."};
std::regex regex{R"([\s,]+)"}; // split on space and comma
std::sregex_token_iterator it{s.begin(), s.end(), regex, -1};
std::vector<std::string> words{it, {}};
这里是仅使用的std :: string ::找一个C++ 11溶液()。分隔符可以是任意数量的字符。解析令牌通过输出迭代器输出,通常是我的代码中的std :: back_inserter。
我还没有用UTF-8测试过,但我期望它应该工作,只要输入和分隔符都是有效的UTF-8字符串。
#include <string>
template<class Iter>
Iter splitStrings(const std::string &s, const std::string &delim, Iter out)
{
if (delim.empty()) {
*out++ = s;
return out;
}
size_t a = 0, b = s.find(delim);
for (; b != std::string::npos;
a = b + delim.length(), b = s.find(delim, a))
{
*out++ = std::move(s.substr(a, b - a));
}
*out++ = std::move(s.substr(a, s.length() - a));
return out;
}
一些测试用例:
void test()
{
std::vector<std::string> out;
size_t counter;
std::cout << "Empty input:" << std::endl;
out.clear();
splitStrings("", ",", std::back_inserter(out));
counter = 0;
for (auto i = out.begin(); i != out.end(); ++i, ++counter) {
std::cout << counter << ": " << *i << std::endl;
}
std::cout << "Non-empty input, empty delimiter:" << std::endl;
out.clear();
splitStrings("Hello, world!", "", std::back_inserter(out));
counter = 0;
for (auto i = out.begin(); i != out.end(); ++i, ++counter) {
std::cout << counter << ": " << *i << std::endl;
}
std::cout << "Non-empty input, non-empty delimiter"
", no delimiter in string:" << std::endl;
out.clear();
splitStrings("abxycdxyxydefxya", "xyz", std::back_inserter(out));
counter = 0;
for (auto i = out.begin(); i != out.end(); ++i, ++counter) {
std::cout << counter << ": " << *i << std::endl;
}
std::cout << "Non-empty input, non-empty delimiter"
", delimiter exists string:" << std::endl;
out.clear();
splitStrings("abxycdxy!!xydefxya", "xy", std::back_inserter(out));
counter = 0;
for (auto i = out.begin(); i != out.end(); ++i, ++counter) {
std::cout << counter << ": " << *i << std::endl;
}
std::cout << "Non-empty input, non-empty delimiter"
", delimiter exists string"
", input contains blank token:" << std::endl;
out.clear();
splitStrings("abxycdxyxydefxya", "xy", std::back_inserter(out));
counter = 0;
for (auto i = out.begin(); i != out.end(); ++i, ++counter) {
std::cout << counter << ": " << *i << std::endl;
}
std::cout << "Non-empty input, non-empty delimiter"
", delimiter exists string"
", nothing after last delimiter:" << std::endl;
out.clear();
splitStrings("abxycdxyxydefxy", "xy", std::back_inserter(out));
counter = 0;
for (auto i = out.begin(); i != out.end(); ++i, ++counter) {
std::cout << counter << ": " << *i << std::endl;
}
std::cout << "Non-empty input, non-empty delimiter"
", only delimiter exists string:" << std::endl;
out.clear();
splitStrings("xy", "xy", std::back_inserter(out));
counter = 0;
for (auto i = out.begin(); i != out.end(); ++i, ++counter) {
std::cout << counter << ": " << *i << std::endl;
}
}
预期输出:
Empty input: 0: Non-empty input, empty delimiter: 0: Hello, world! Non-empty input, non-empty delimiter, no delimiter in string: 0: abxycdxyxydefxya Non-empty input, non-empty delimiter, delimiter exists string: 0: ab 1: cd 2: !! 3: def 4: a Non-empty input, non-empty delimiter, delimiter exists string, input contains blank token: 0: ab 1: cd 2: 3: def 4: a Non-empty input, non-empty delimiter, delimiter exists string, nothing after last delimiter: 0: ab 1: cd 2: 3: def 4: Non-empty input, non-empty delimiter, only delimiter exists string: 0: 1:
分裂的空间?我不认为C++ 11在这里添加了任何东西,认为[接受的答案](http://stackoverflow.com/a/237280/845092)仍然是最好的方法。 – 2012-02-24 17:42:09
分裂后你想要什么?打印到cout?或者得到一个子串的向量? – balki 2012-02-24 17:42:37
这不是正则表达式解析的用途吗? – 2012-02-24 17:46:58