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

时间:2013-09-04 21:48:00

标签: c++ string split

如何在空格中分割字符串并返回第一个元素?例如,在Python中你可以这样做:

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

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

1 个答案:

答案 0 :(得分:8)

为什么要分开整个字符串并在整个过程中制作每个标记的副本,因为你最后会抛出它们(因为你只需要第一个标记)?

在您的具体案例中,只需使用std::string::find()

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

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

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