[英]split a string using multiple delimiters (including delimiters) in c++
I have a string which I input as follows我有一个字符串,我输入如下
using namespace std;
string s;
getline(cin, s);
I input我输入
ab~cd
ab~cd
I want to split the string at .
我想在
.
and ~
but also want to store the delimiters.和
~
但也想存储分隔符。 The split elements will be stored in a vector.拆分的元素将存储在一个向量中。
Final output should look like this最终输出应如下所示
a
.
b
~
c
.
d
I saw a solution here but it was in java.我在这里看到了一个解决方案,但它是在 Java 中的。
How do I achieve this in c++?我如何在 C++ 中实现这一点?
This solution is copied verbatim from this answer except for the commented lines:除了注释行外,此解决方案是从这个答案中逐字复制的:
std::stringstream stringStream(inputString);
std::string line;
while(std::getline(stringStream, line))
{
std::size_t prev = 0, pos;
while ((pos = line.find_first_of(".~", prev)) != std::string::npos) // only look for . and ~
{
if (pos > prev)
wordVector.push_back(line.substr(prev, pos-prev));
wordVector.push_back(line.substr(pos, 1)); // add delimiter
prev = pos+1;
}
if (prev < line.length())
wordVector.push_back(line.substr(prev, std::string::npos));
}
I haven't tested the code, but the basic idea is you want to store the delimiter character in the result as well.我还没有测试过代码,但基本的想法是你也想在结果中存储分隔符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.