如何在C ++中将空格分隔的字符串拆分为多个字符串? [英] How to split a space separated string into multiple strings in 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("\t "));
这篇关于如何在C ++中将空格分隔的字符串拆分为多个字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!