例如我有一个字符串:
string s = "apple | orange | kiwi";
Run Code Online (Sandbox Code Playgroud)
我搜索了,有一种方法:
stringstream stream(s);
string tok;
getline(stream, tok, '|');
Run Code Online (Sandbox Code Playgroud)
但它只能返回第一个标记"apple"我想知道有什么方法可以返回一个字符串数组吗?谢谢.假设可以改变字符串s.例如,字符串s ="apple | orange | kiwi | berry";
Lig*_*ica 33
正如本杰明指出的那样,你在标题中自己回答了这个问题.
#include <sstream>
#include <vector>
#include <string>
int main() {
// inputs
std::string str("abc:def");
char split_char = ':';
// work
std::istringstream split(str);
std::vector<std::string> tokens;
for (std::string each; std::getline(split, each, split_char); tokens.push_back(each));
// now use `tokens`
}
Run Code Online (Sandbox Code Playgroud)
请注意,您的令牌仍将具有尾随/前导<space>字符.你可能想把它们剥掉.