Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
320 views
in Technique[技术] by (71.8m points)

c++ - use getline and while loop to split a string

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...