在C++中,将字符串按空格拆分并返回第一个元素

9
我该如何在空格处分割字符串并返回第一个元素?例如,使用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;
}

你看过这个吗?我真的分不清这有什么不同。 - chris
哦,让分割返回列表是最优的。从我看到的情况来看,这段C++代码会返回像“one”、“two”、“thirty-four”这样的结果。 - riyoken
可能需要通过类似于for循环的东西来运行它。 - riyoken
1个回答

19
为什么要将整个字符串拆分并在途中复制每个标记,因为最终你会将它们丢弃(因为你只需要第一个标记)?
在您非常特定的情况下,只需使用std::string::find()
std::string s = "one two three";
auto first_token = s.substr(0, s.find(' '));

请注意,如果未找到空格字符,则您的标记将是整个字符串。
(当然,在C++03中,用适当的类型名称替换auto,即std::string

1
它返回一个索引。你可以使用auto first_token = s.substr(0, s.find(' '));来实现。 - chris
@chris 哦,我想我把标准库中的其他“查找”算法搞混了。我的错。 - syam
1
是的,std::find 返回一个迭代器。 - chris
禁止声明无类型的it/first_token。 - riyoken
没事,我没有看到“用适当的类型替换auto”。 - riyoken

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接