Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

string

split

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;
}
like image 712
riyoken Avatar asked Sep 04 '13 21:09

riyoken


People also ask

How do you get your first element after a split?

To split a string and get the first element of the array, call the split() method on the string, passing it the separator as a parameter, and access the array element at index 0 . For example, str. split(',')[0] splits the string on each comma and returns the first array element.

How do you split a string into the first space?

split() method with array destructuring to split a string only on the first occurrence of a character, e.g. const [first, ... rest] = str. split('-'); . The array destructuring syntax will capture the two parts of the string in separate variables.

Does split () alter the original string?

Note: The split() method does not change the original string. Remember – JavaScript strings are immutable. The split method divides a string into a set of substrings, maintaining the substrings in the same order in which they appear in the original string. The method returns the substrings in the form of an array.

How do you split a string into elements?

Python split() method is used to split the string into chunks, and it accepts one argument called separator. A separator can be any character or a symbol. If no separators are defined, then it will split the given string and whitespace will be used by default.


1 Answers

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)

like image 85
syam Avatar answered Oct 22 '22 21:10

syam