9

How do I split string at space and return first element? For example, in Python you would do:

string = 'hello how are you today'
ret = string.split(' ')[0]
print(ret)
'hello'

Doing this in C++, I would imagine that I would need to split the string first. Looking at this online, I have seen several long methods, but what would be the best one that works like the code above? An example for a C++ split that I found is

#include <boost/regex.hpp>
#include <boost/algorithm/string/regex.hpp>
#include <iostream>
#include <string>
#include <vector>

using namespace std;
using namespace boost;

void print( vector <string> & v )
{
  for (size_t n = 0; n < v.size(); n++)
    cout << "\"" << v[ n ] << "\"\n";
  cout << endl;
}

int main()
{
  string s = "one->two->thirty-four";
  vector <string> fields;

  split_regex( fields, s, regex( "->" ) );
  print( fields );

  return 0;
}
VLL
  • 9,634
  • 1
  • 29
  • 54
riyoken
  • 574
  • 2
  • 7
  • 17
  • Did you come across [this](http://stackoverflow.com/questions/236129/splitting-a-string-in-c?rq=1)? I can't really tell how this is any different. – chris Sep 04 '13 at 21:49
  • oh and getting the split to return as a list is optimal. from what i have seen this c++ code returns it like "one" "two" "thirty-four" – riyoken Sep 04 '13 at 21:57
  • probably run that through something like a for loop though. – riyoken Sep 04 '13 at 21:58

1 Answers1

19

Why bother with splitting the whole string and making copies of every token along the way since you will throw them in the end (because you only need the first token)?

In your very specific case, just use std::string::find():

std::string s = "one two three";
auto first_token = s.substr(0, s.find(' '));

Note that if no space character is found, your token will be the whole string.

(and, of course, in C++03 replace auto with the appropriate type name, ie. std::string)

syam
  • 14,701
  • 3
  • 41
  • 65