[C++]对string按指定分隔符分割(split)

一、摘要

本文介绍了一种使用<string>头文件中的getline()函数和一种使用istream_iterato<T>模板类进行字符串分割的方法。

二、代码

1. 使用getline()函数

#include <iostream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
int main() {
    string origin_str = "hello world !"; // 需要进行分割的字符串
    stringstream ss(origin_str);         // 使用字符串构造一个stringstream类型(流)数据
    char c = ' '; // 设定好分隔符号(只能使用一个字符进行分割)
    vector<string> results; // 用来存储结果
    string str; //用来接收每个分割的字符串
    // 开始分隔
    while (getline(ss, str, c)) {
        results.push_back(str);
    }
    for (int i = 0; i < results.size(); i++) {
        cout << results[i] << endl;
    }
    return 0;
}

注意:使用getline()string进行分割只能按照单个字符进行分割,不能使用子字符串分割!!!

2. 使用istream_iterator模板类

#include <iostream>
#include <string>
#include <sstream>
#include <iterator>
#include <fstream>
using namespace std;
int main(int argc, char** argv) {
    string str = "hello world";	// 需要进行分割的字符串
    stringstream ss(str);	// 使用字符串构造一个stringstream类型(流)数据
    istream_iterator<string, char> it(ss);	//使用字符串构造一个istream_iterator类型(迭代器)数据

    while (it != istream_iterator<string>{}) {	// 迭代取出各个元素
        cout << *it << " ";
        it++;
    }
    return 0;
}

注意:使用istream_iterator<T>string进行分割只能按照默认的流分割符号进行分割,例如空格和回车。如果需要使用其他自定义符号进行分割,也有其他修改分割符的方法,但那是另外的知识点了此处不再涉及。

四、参考引用

[1]. [C/C++标准库][初级][分割字符串Split]
[2]. std::istream_iterator

posted on   刘好念  阅读(2478)  评论(0编辑  收藏  举报  

相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示