gpt4 book ai didi

c++ - 如何在 C++ 中将空格分隔的字符串拆分为多个字符串?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:15:46 25 4
gpt4 key购买 nike

我的代码如下所示:

static int myfunc(const string& stringInput)
{
string word;
stringstream ss;

ss << stringInput;
while(ss >> word)
{
++counters[word];
}
...
}

这里的目的是获取一个输入字符串(以空格''分隔)到字符串变量word中,但是这里的代码似乎有很大的开销——转换输入字符串到字符串流并从字符串流中读入目标字符串。

是否有更优雅的方式来实现相同的目的?

最佳答案

你问的是如何分割一个字符串。 Boost 有一个有用的工具 boost::split()

http://www.boost.org/doc/libs/1_48_0/doc/html/string_algo/usage.html#id3115768

这是一个将生成的单词放入 vector 中的示例:

#include <boost/algorithm/string.hpp>
std::vector<std::string> strs;
boost::split(strs, "string to split", boost::is_any_of("\t "));

关于c++ - 如何在 C++ 中将空格分隔的字符串拆分为多个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8683302/

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