4

Is there a split type function for C++ similar to Java? I know of ignore, but I don't quite understand it, and how it'll work for my case.

My input is:

{
  item = ball
  book = lord of the rings
  movie = star wars
}

My input given is an <attribute> = <value> and I have to store the two in different strings, or integers (depending on the value, for example, if its a number, use an integer).

kaya3
  • 47,440
  • 4
  • 68
  • 97
SNpn
  • 2,157
  • 8
  • 36
  • 53
  • What do you mean by 'ignore', and why do you think that templates have anything much to do with splitting strings? See the doc for std::string to see what it's got. – bmargulies Sep 28 '11 at 12:20
  • @bmargulies there is a `str.split("=")` type function in the `java` API and there is a cin.ignore(1,"=")` type function in the `c++` API, I've tried using the ignore, but I'm lost in how to just get rid of the paranthese – SNpn Sep 28 '11 at 12:23
  • 1
    possible duplicate of [How to split a string in C++?](http://stackoverflow.com/questions/236129/how-to-split-a-string-in-c) – Pablo Santa Cruz Sep 28 '11 at 12:24
  • I think he can use the answer from that (I actually threw it in mine), but he could have been looking for something to just tokenize by the = sign which wouldn't be covered by that question - so I think it's a little different. – John Humphreys Sep 28 '11 at 12:28

2 Answers2

6

Use Boost::tokenizer as it does what you want to do. From the manual:

// simple_example_1.cpp
#include<iostream>
#include<boost/tokenizer.hpp>
#include<string>

int main(){
   using namespace std;
   using namespace boost;
   string s = "This is,  a test";
   tokenizer<> tok(s);
   for(tokenizer<>::iterator beg=tok.begin(); beg!=tok.end();++beg){
       cout << *beg << "\n";
   }
}
Sardathrion - against SE abuse
  • 17,269
  • 27
  • 101
  • 156
0

Use strtok(): http://www.cplusplus.com/reference/clibrary/cstring/strtok/.

Just know that its not re-entrant because it uses an internal static variable, so don't call it twice in nested loops or anything like that.

and EDIT:

This is a very cool SO solution that would tokenize the whole string by spaces - you'd have to process the values back together after the = but it would teach you STL well :)

Split a string in C++?

Community
  • 1
  • 1
John Humphreys
  • 37,047
  • 37
  • 155
  • 255
  • 1
    If it's not re-entrant enough to call in nested loops it's definitely not thread safe - I figured anyone asking how to split a string didn't need to worry about that complexity though :p – John Humphreys Sep 28 '11 at 12:58
  • @w00te strtok won't work in my case...since I can have input similar to `item = baseball bat` and baseball bat has to be one string, strtok would split that up into two words – SNpn Sep 28 '11 at 13:27