在空格处拆分字符串并返回C++中的第一个元素

riy*_*ken 5 c++ string split

如何在空间拆分字符串并返回第一个元素?例如,在Python中你会这样做:

string = 'hello how are you today'
ret = string.split(' ')[0]
print(ret)
'hello'
Run Code Online (Sandbox Code Playgroud)

在C++中这样做,我想我需要先拆分字符串.在网上看到这个,我已经看到了几个很长的方法,但最好的方法是什么,就像上面的代码一样?我发现的C++拆分的一个例子是

#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;
}
Run Code Online (Sandbox Code Playgroud)

sya*_*yam 10

为什么要分开整个字符串并制作每个令牌的副本,因为你最终会抛出它们(因为你只需要第一个令牌)?

在您的具体情况下,只需使用std::string::find():

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

请注意,如果未找到空格字符,则您的标记将是整个字符串.

(当然,在C++ 03 auto中用适当的类型名称替换,即.std::string)