使用getline和while循环来拆分字符串 [英] use getline and while loop to split a string

查看:189
本文介绍了使用getline和while循环来拆分字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如我有一个字符串:

string s = "apple | orange | kiwi";

我搜索并且有一种方法:

and i searched and there is a way:

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

但它只能返回第一个令牌apple
我不知道有没有方式所以它可以返回一个字符串数组?
谢谢。
假设字符串s可以更改。例如,string s =apple | orange | kiwi | berry;

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";

推荐答案

Benjamin指出,

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

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

注您的令牌仍将具有尾随/前导< space> 字符。您可以删除它们。

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

这篇关于使用getline和while循环来拆分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆