【发布时间】:2019-03-02 15:08:57
【问题描述】:
有没有办法将字符串分成小部分并存储到向量中。
例如:
一个字符串:str = "(a b c) d e f [[g h i]]"。预期的输出是:
(a b c)
d e f
[[g h i]]
示例代码:
vector<string> token;
string str = "(a b c)d e f[[g h i]]";
string bracketS = "()[]";
istringstream ss(str);
string section;
string tok;
while (getline(ss,section)) {
size_t start = 0;
size_t end = section.find_first_of(bracketS);
while (end != string::npos) {
tok = section.substr(start, end - start);
token.push_back(tok);
start = end + 1;
end = section.find_first_of(bracketS, start);
}
}
输出没有括号:
a b c
d e f
g h i
试图调整我的section.substr(start-1, end - start+2)
那么我的输出是:
(a b c)
) d e f [
[g h i]
为什么中间的向量是错误的。
也试过做strtok。但是输出和第一个一样。
还有其他方法吗?
【问题讨论】:
-
简单地使用
std::regex怎么样? -
如果您对正则表达式一无所知,但对基本数据结构有一点了解,您可以尝试
std::stack并知道何时可以使用 topush和pop,然后不需要strtok。您尝试使用“蛮力”解析是一种天真的方法。 -
@PaulMcKenzie 谢天谢地,OP 根本没有在他们的代码中使用
strtok(),还是我错过了什么? -
@πάνταῥεῖ OP 在他的帖子中提到了
strtok。 -
不清楚你想用嵌套括号做什么。例如,
(a b c) (d [e f] g)的结果是什么?
标签: c++ string vector data-structures split