如何在 C++ 中将空格分隔的字符串拆分为多个字符串? [英] How to split a space separated string into multiple strings in C++?

查看:28
本文介绍了如何在 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++ 中将空格分隔的字符串拆分为多个字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆