字符串的分割
2022-01-07 本文已影响0人
NHFX
字符串的分割
示例一
使用C++2.0,模仿php中explode方法的功能。
#include <iostream>
#include <string>
#include <vector>
// MARK: - The definition of explode
// The given delimiter is limited to a single char only
const std::vector<std::string> explode(const std::string &src, const char &c) {
std::vector<std::string> result;
result.clear();
if (src.empty()) {
return result;
}
std::string buffer{""};
for (auto n : src) {
if (n != c) {
buffer += n;
} else if(n == c && !buffer.empty()){
result.emplace_back(buffer);
buffer.clear();
}
}
if(!buffer.empty()) {
result.emplace_back(buffer);
buffer.clear();
}
return result;
}
// MARK: - Main 入口
int main(int argc, char *argv[])
{
std::string text {"We can write a explode fuction using C++."};
std::vector<std::string> res{explode(text, ' ')};
for(auto elem: res)
std::cout << elem << std::endl;
return 0;
}
示例2
利用正则方法 std::regex,std::regex类的使用可以参考
https://blog.csdn.net/qq_28087491/article/details/107608569
#include <iostream>
#include <string>
#include <vector>
#include <regex>
std::vector<std::string> split(const std::string& src, const std::string& regex) {
// passing -1 as the submatch index parameter performs splitting
std::regex re(regex);
std::sregex_token_iterator
first{src.begin(), src.end(), re, -1},
last;
return {first, last};
}
// MARK: - Main 入口
int main(int argc, char *argv[])
{
std::string text {"We can write a explode fuction using C++."};
std::vector<std::string> res{split(text, " ")};
for(auto elem: res)
std::cout << elem << std::endl;
return 0;
}
更多的分割方法
https://stackoverflow.com/questions/9435385/split-a-string-using-c11