Let's say I have a std::string "55|6999|dkfdfd|". It cointains 3 parts (each is followed by |). Currently I put the string to stringstream and I use getline to recover them. However I wonder if there is a simpler solution which doesn't require streams. I just need an easy way to getline from that string using '|' as delim, as I think streams are overkill for it and I'm doing it wrong.
Asked
Active
Viewed 177 times
3 Answers
2
If boost is permitted then boost::split
would be an option. It can be used to populate a std::vector<std::string>
, which would contain the fields extracted from input based on specified delimiter(s):
#include <vector>
#include <string>
using std::vector;
using std::string;
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/split.hpp>
using boost::split;
using boost::is_any_of;
vector<string> fields;
split(fields, "55|6999|dkfdfd|", is_any_of("|"));

hmjd
- 120,187
- 20
- 207
- 252
1
You could use std::strtok
instead:
char *token = std::strtok(<yourstring>, "|");
< yourstring > has to be of type char*
though; and then use NULL
for the ones after that, std::strtok
keeps track of the previously used string.
token = std::strtok(NULL, "|");

imreal
- 10,178
- 2
- 32
- 48
-
@user1873947, note `strtok` modifies the input so using a string literal would be illegal for example. – hmjd Feb 12 '13 at 18:06
1
What you are talking about is called "tokenizing" a string. That would be generally your best bet. As for how to do it, see "How do I tokenize a string in C++?"

Community
- 1
- 1