简体   繁体   中英

Split string at space and return first element in C++

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

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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM