C++ 中是否有 PHP 的 expand() 函数的等价物? [英] Is there an equivalent in C++ of PHP's explode() function?

查看:58
本文介绍了C++ 中是否有 PHP 的 expand() 函数的等价物?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
在 C++ 中拆分字符串

在 PHP 中,explode() 函数将接受一个字符串并将其分割成一个数组,用指定的分隔符分隔每个元素.

In PHP, the explode() function will take a string and chop it up into an array separating each element by a specified delimiter.

C++ 中是否有等效的函数?

Is there an equivalent function in C++?

推荐答案

这是一个简单的示例实现:

Here's a simple example implementation:

#include <string>
#include <vector>
#include <sstream>
#include <utility>

std::vector<std::string> explode(std::string const & s, char delim)
{
    std::vector<std::string> result;
    std::istringstream iss(s);

    for (std::string token; std::getline(iss, token, delim); )
    {
        result.push_back(std::move(token));
    }

    return result;
}

用法:

auto v = explode("hello world foo bar", ' ');

注意:@Jerry 写入输出迭代器的想法更符合 C++ 的习惯.事实上,您可以同时提供两者;一个输出迭代器模板和一个生成向量的包装器,以实现最大的灵活性.

Note: @Jerry's idea of writing to an output iterator is more idiomatic for C++. In fact, you can provide both; an output-iterator template and a wrapper that produces a vector, for maximum flexibility.

注意2:如果你想跳过空标记,添加if (!token.empty()).

Note 2: If you want to skip empty tokens, add if (!token.empty()).

这篇关于C++ 中是否有 PHP 的 expand() 函数的等价物?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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