How to split a space separated string into multiple strings in C++?(如何在 C++ 中将空格分隔的字符串拆分为多个字符串?)
问题描述
我的代码如下所示:
static int myfunc(const string& stringInput)
{
string word;
stringstream ss;
ss << stringInput;
while(ss >> word)
{
++counters[word];
}
...
}
这里的目的是获取一个输入字符串(用空格''分隔)到字符串变量word
中,但是这里的代码好像开销很大——转换输入字符串到字符串流并从字符串流中读取到目标字符串中.
The purpose here is to get an input string (separated by white space ' ') into the string variable word
, but the code here seems to have a lot of overhead -- convert the input string to a string stream and read from the string stream into the target string.
有没有更优雅的方式来实现同样的目的?
Is there a more elegant way to accomplish the same purpose?
推荐答案
您问的是如何拆分字符串.Boost 有一个有用的工具 boost::split()
You are asking how to split a string. Boost has a helpful utility boost::split()
http://www.boost.org/doc/libs/1_48_0/doc/html/string_algo/usage.html#id3115768
这是一个将结果词放入向量的示例:
Here's an example that puts the resulting words into a vector:
#include <boost/algorithm/string.hpp>
std::vector<std::string> strs;
boost::split(strs, "string to split", boost::is_any_of(" "));
这篇关于如何在 C++ 中将空格分隔的字符串拆分为多个字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 C++ 中将空格分隔的字符串拆分为多个字符串?


基础教程推荐
- 常量变量在标题中不起作用 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01