c++字符串的spilit
字符串分割是处理字符串的常见问题,以下提供几种解决方案。
初始版本
#include <iostream>
#include <string>
#include <regex>
#include <vector>
// 采用正则版本
std::vector<std::string> split(std::string &text)
{
std::regex ws_re("\\s+"); // white space
return std::vector<std::string>(std::sregex_token_iterator(text.begin(), text.end(), ws_re, -1), std::sregex_token_iterator());
}
//优雅版本
void split(const std::string &text, std::vector<std::string> &tokens, const std::string &delimiter = " ") {
std::string::size_type lastPos = text.find_first_not_of(delimiter, 0);
std::string::size_type pos = text.find_first_of(delimiter, lastPos);
while (std::string::npos != pos || std::string::npos != lastPos) {
tokens.emplace_back(text.substr(lastPos, pos - lastPos));
lastPos = text.find_first_not_of(delimiter, pos);
pos = text.find_first_of(delimiter, lastPos);
}
}
void test() {
std::string str{"quick brown fox"};
std::vector<std::string> t1 = split(str);
std::cout << "regex 版本\n";
for (auto s : t1) std::cout << s << std::endl;
std::vector<std::string> t2;
split(str, t2);
std::cout << "优雅版本\n";
for (auto s : t2) std::cout << s << std::endl;
}
int main() {
test();
}
新版本,使用stream
,该版本能只能分割空格字符,后续可以改进分割
std::vector<std::string> split(const std::string& text) {
std::istringstream iss(text);
std::vector<std::string> res((std::istream_iterator<std::string>(iss)),
std::istream_iterator<std::string>());
return res;
}
非标准,但对任意delimiter
都能用,接口清晰
std::vector<std::string> split(const std::string& s, const char delimiter)
{
std::vector<std::string> tokens;
std::string tokens;
std::istringstream tokenStream(s);
while(std::getline(tokenStream, token, delimiter))
{
tokens.push_back(token);
}
return tokens;
}
原文链接: https://www.cnblogs.com/codemeta-2020/p/12515875.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/194489
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!