[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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值