Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $YECBGYFECGEAFWHA as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2

Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $BBWFDDBHHYHDXXAB as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2
C++如何根据分隔符拆分字符串_C++ getline与stringstream分割技巧_创想鸟

C++如何根据分隔符拆分字符串_C++ getline与stringstream分割技巧

C++中可通过stringstream与getline按单字符分隔符拆分字符串,适用于解析CSV等场景;2. 默认保留空字段,可添加!token.empty()过滤;3. 多字符分隔需用find与substr实现。

c++如何根据分隔符拆分字符串_c++ getline与stringstream分割技巧

在C++中,根据分隔符拆分字符串是一个常见需求,比如解析CSV数据、读取配置文件等。虽然标准库没有直接提供类似Python的split函数,但可以借助getline和stringstream高效实现灵活的字符串分割。

使用stringstream与getline按分隔符拆分

stringstream结合getline是C++中最常用的字符串分割方法。getline支持自定义分隔符,能逐段提取子字符串并存入容器。

基本思路:将字符串载入istringstream,然后用带分隔符参数的getline循环读取字段。

包含头文件:#include 、#include 、#include 创建istringstream对象加载原字符串 循环调用getline(ss, token, delimiter)提取每个片段 将token加入vector或其他容器

示例代码:

立即学习“C++免费学习笔记(深入)”;

#include iostream>
#include
#include
#include

std::vector split(const std::string& str, char delim) {
    std::vector result;
    std::istringstream ss(str);
    std::string token;
    while (std::getline(ss, token, delim)) {
        result.push_back(token);
    }
    return result;
}

int main() {
    std::string input = “apple,banana,orange”;
    auto parts = split(input, ‘,’);
    for (const auto& s : parts) {
        std::cout     }
    return 0;
}

处理连续分隔符与空字段

默认情况下,getline不会跳过空字段。例如”a,,b”用逗号分割会得到三个元素,中间一个是空字符串。这在解析CSV时可能是期望行为。

若需忽略空项,可在插入前判断token是否为空:

添加条件:if (!token.empty()) 才加入结果 适用于去除首尾或中间多余分隔符产生的空串 注意:开头或结尾的分隔符也可能产生空字段

修改后的split函数片段:

while (std::getline(ss, token, delim)) {
    if (!token.empty()) {
        result.push_back(token);
    }
}

支持多字符分隔符的替代方案

getline只支持单字符分隔符。若需按字符串(如”||”)拆分,标准库方法不再适用。

此时可使用std::string的find和substr组合处理:

用find查找分隔符位置 用substr截取子串 更新起始位置继续搜索 适合复杂分隔场景,但代码稍繁琐

基本上就这些。对于大多数情况,stringstream配合getline已足够高效且易用。掌握这一技巧能大幅提升字符串处理能力。

以上就是C++如何根据分隔符拆分字符串_C++ getline与stringstream分割技巧的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1488396.html

赞 (0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
C++ string反转_C++ reverse函数翻转字符串
上一篇 2025年12月19日 11:31:09
C++怎么实现一个线程池_C++高性能并发模型与ThreadPool设计
下一篇 2025年12月19日 11:31:21

相关推荐

发表回复

登录后才能评论
关注微信