C++ 如何使用 stringstream 分隔逗号分隔的字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11719538/
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-27 15:28:39  来源:igfitidea点击:

How to use stringstream to separate comma separated strings

c++tokenizestringstream

提问by Meysam

I've got the following code:

我有以下代码:

std::string str = "abc def,ghi";
std::stringstream ss(str);

string token;

while (ss >> token)
{
    printf("%s\n", token.c_str());
}

The output is:

输出是:

abc
def,ghi

abc
def,ghi

So the stringstream::>>operator can separate strings by space but not by comma. Is there anyway to modify the above code so that I can get the following result?

所以stringstream::>>操作符可以用空格分隔字符串,但不能用逗号分隔。无论如何修改上面的代码,以便我可以获得以下结果?

input: "abc,def,ghi"

output:
abc
def
ghi

输入:“abc,def,ghi”

输出
abc
def
ghi

回答by jrok

#include <iostream>
#include <sstream>

std::string input = "abc,def,ghi";
std::istringstream ss(input);
std::string token;

while(std::getline(ss, token, ',')) {
    std::cout << token << '\n';
}

abc
def
ghi

abc
def
ghi

回答by Kish

#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
    std::string input = "abc,def,   ghi";
    std::istringstream ss(input);
    std::string token;
    size_t pos=-1;
    while(ss>>token) {
      while ((pos=token.rfind(',')) != std::string::npos) {
        token.erase(pos, 1);
      }
      std::cout << token << '\n';
    }
}