Joh*_*esD 59
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};
}
Run Code Online (Sandbox Code Playgroud)
Yag*_*ang 21
这是一种(可能不那么冗长)分割字符串的方式(基于你提到的帖子).
#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;
}
Run Code Online (Sandbox Code Playgroud)
fdu*_*uff 12
这是一个分割字符串并使用提取的元素填充向量的示例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");
Run Code Online (Sandbox Code Playgroud)
另一个正则表达式解决方案受到其他答案的启发,但希望更短更容易阅读:
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, {}};
Run Code Online (Sandbox Code Playgroud)
我不知道这是否不那么冗长,但对于那些在动态语言(例如 javascript)方面经验丰富的人来说,可能更容易理解。它使用的唯一 C++11 特性是 lambdas。
#include <string>
#include <cctype>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
string s = "hello how are you won't you tell me your name";
vector<string> tokens;
string token;
for (const auto& c: s) {
if (!isspace(c))
token += c;
else {
if (token.length()) tokens.push_back(token);
token.clear();
}
}
if (token.length()) tokens.push_back(token);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
88054 次 |
| 最近记录: |