1

I have ;

 string  str = "";

in str, I store data is in following form "_ : _, _ " "_" can be just a word like "X" or a composition of words like "a sds 23 dsds 1"

I want them parse it to three different string ;

in str       : X:y dfj kd kk,sdd 12 89 ++
string parsed[i] ;
in parsed[0] : X
in parsed[1] : y dfj kd kk
in parsed[2] : sdd 12 89 ++

How can I do that over using c++ std::string features ?

  • What is the string format? What is the rule to break up `str`? – wallyk May 17 '11 at 08:31
  • 1
    possible duplicate of [Parsing a comma-delimited std::string](http://stackoverflow.com/questions/1894886/parsing-a-comma-delimited-stdstring) – Bo Persson May 17 '11 at 08:36
  • or this: [how do I tokenize a string in c](http://stackoverflow.com/questions/53849/how-do-i-tokenize-a-string-in-c) – StevieG May 17 '11 at 08:54
  • http://stackoverflow.com/questions/236129/how-to-split-a-string – cpx May 17 '11 at 09:24

2 Answers2

1

You can split your string using the following std:string methods for example:

size_t index1 = str.find( ":" ) + 1;
size_t index2 = str.find( ",", index1 ) + 1;

std::string sub1 = str.substr (0, index1-1);
std::string sub2 = str.substr (index1, index2-index1-1);
std::string sub3 = str.substr (index2, str.length()-index2);
Valkea
  • 1,216
  • 1
  • 12
  • 26
0

Using boost/algorithm/string.hpp

std::string str = "X:y dfj kd kk,sdd 12 89 ++"
std::vector<std::string> v;
boost::split(v, str, boost::is_any_of(":,"));

You can also use it for multibyte strings.

cpx
  • 17,009
  • 20
  • 87
  • 142