gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:11:04 24 4
gpt4 key购买 nike

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

最佳答案

为什么要拆分整个字符串并沿途复制每个标记,因为您将在最后抛出它们(因为您只需要第一个标记)?

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

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

请注意,如果没有找到空格字符,您的 token 将是整个字符串。

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

关于c++ - 在空格处拆分字符串并返回 C++ 中的第一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18624345/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com