C++ 使用 getline 和 while 循环拆分字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5757721/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 18:49:09  来源:igfitidea点击:

use getline and while loop to split a string

c++

提问by Xitrum

for example i have a string:

例如我有一个字符串:

string s = "apple | orange | kiwi";

and i searched and there is a way:

我搜索了一下,有一种方法:

stringstream stream(s);
string tok;
getline(stream, tok, '|');

but it only can return the first token "apple" I wonder that is there any way so it can return an array of string? Thank you. Let assume that the string s may be changed. For exammple, string s = "apple | orange | kiwi | berry";

但它只能返回第一个标记“苹果”我想知道有什么方法可以返回一个字符串数组吗?谢谢你。假设字符串 s 可能会改变。例如,字符串 s = "apple | orange | kiwi | berry";

回答by Lightness Races in Orbit

As Benjamin points out, you answered this question yourself in its title.

正如 Benjamin 指出的那样,您自己在标题中回答了这个问题。

#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`
}

Note that your tokens will still have the trailing/leading <space>characters. You may want to strip them off.

请注意,您的令牌仍将具有尾随/前导<space>字符。你可能想把它们剥掉。

回答by Nawaz

Since there is space between each word and |, you can do this:

由于每个单词 和 之间有空格|,您可以这样做:

string s = "apple | orange | kiwi";
stringstream ss(s);
string toks[3];
string sep;
ss >> toks[0] >> sep >> toks[1] >> sep >> toks[2];

cout << toks[0] <<", "<< toks[1] <<", " << toks[2];

Output:

输出:

apple, orange, kiwi

Demo : http://www.ideone.com/kC8FZ

演示:http: //www.ideone.com/kC8FZ

Note: it will work as long as there is atleast one space between each word and |. That means, it will NOT work if you've this:

注意:只要每个单词和 之间至少有一个空格,它就会起作用|。这意味着,如果你有这个,它就行不通:

string s = "apple|orange|kiwi";


Boost is a good if you want robust solution. And if you don't want to use boost for whatever reason, then I would suggest you to see this blog:

如果你想要健壮的解决方案,Boost 是一个很好的选择。如果您出于任何原因不想使用 boost,那么我建议您查看此博客:

Elegant ways to tokenize strings

标记字符串的优雅方法

It explains how you can tokenize your strings, with just one example.

它仅通过一个示例说明了如何标记字符串。