How to use stringstream to separate comma separated strings
本问题已经有最佳答案,请猛点这里访问。
我有以下代码:
1 2 3 4 5 6 7 8 9 10 | std::string str ="abc def,ghi"; std::stringstream ss(str); string token; while (ss >> token) { printf("%s ", token.c_str()); } |
输出是:
abc
def,ghi
因此,
input:"abc,def,ghi"
output:
abc
def
ghi
1 2 3 4 5 6 7 8 9 10 11 | #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 << ' '; } |
abc
def
ghi
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | #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 << ' '; } } |