我在此处使用此代码进行字符串拆分:string split
char sep = ' ';
std::string s="1 This is an exampl";
for(size_t p=0, q=0; p!=s.npos; p=q)
std::cout << s.substr(p+(p!=0), (q=s.find(sep, p+1))-p-(p!=0)) << std::endl;
代码运行正常,输出为:
1
This
is
an
exampl
如果我将分隔符从 ' ' 更改为 'e',输出为:
1 This is an
xampl
示例中的“e”丢失了。如何使用相同的代码拆分字符串而不丢失用作分隔符的字母?
最佳答案
我建议使用简单的 \b(?=e)
正则表达式拆分字符串(匹配 e
仅当它前面没有字母、数字或下划线时):
#include <string>
#include <iostream>
#include <regex>
using namespace std;
int main() {
std::vector<std::string> strings;
std::string s = "1 This is an exampl";
std::regex re("\\b(?=e)");
std::regex_token_iterator<std::string::iterator> it(s.begin(), s.end(), re, -1);
decltype(it) end{};
while (it != end){
strings.push_back(*it++);
std::cout << strings[strings.size()-1] << std::endl; // DEMO!
}
return 0;
}
参见 C++ demo .
关于c++ - 在不丢失分隔符的情况下拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40397773/