c++使用stringstream与getline分割字符

本文介绍了如何使用C++中的stringstream来高效地处理字符串,包括按指定分隔符分割字符串的方法,并展示了使用迭代器进行二次迭代的具体实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

stringstream()

#include<sstream>

stringstream可以使string与各种内置类型数据之间的转换

直接用getline()

当我们直接利用getline(),自定义字符,从cin流中分割字符,例如
输入 “one#two”

string str;		
ss << str2;
while (getline(cin, str, '#'))
	cout << str<< endl;
system("pause");
return 0;

输出结果为

one

后面的 two并没有输出

使用stringstream

此时如果我们是用 stringstream 流,例如:

#include<iostream>
#include<string>
#include<sstream>
using namespace std;

int main(){
    string str; 
    string str_cin("one#two#three");
    stringstream ss;
    ss << str_cin;
    
    while (getline(ss, str, '#'))
        cout << str<< endl;
    system("pause");
    return 0;
}

结果:

one
two
three

使用数组
#include<iostream>
#include<string>
#include<sstream>
using namespace std;

int main(){
    int j=0;
    string str, result[3];
    string str_cin("one#two#three");

    stringstream ss;
    ss << str_cin;
    
    //赋值
    while (getline(ss, str, '#')){
        result[j] = str;
        j++;
    }

    //遍历
    for(int i=0; i<3; i++){
        cout<<result[i]<<endl;
    }

    system("pause");
    return 0;
}
使用迭代器
#include<iostream>
#include<string>
#include<sstream>
#include<vector>
using namespace std;

int main(){
    string str;
    vector<string> result;
    string str_cin("one#two#three");

    stringstream ss;
    ss << str_cin;
    
    //赋值
    while (getline(ss, str, '#')){
        result.push_back(str);
    }

    cout<<"迭代器遍历:"<<endl;
    //定义一个迭代器
    vector<string>::iterator iter;
    for(iter = result.begin(); iter != result.end(); iter++){
        cout<<*iter<<endl;
    }

    system("pause");
    return 0;
}

数组&迭代器结果:

one
two
three

二次迭代
#include<iostream>
#include<string>
#include<sstream>
#include<vector>
using namespace std;

int main(){
    string str;
    vector<string> result;
    string str_cin("one#two#three");

    stringstream ss;
    ss << str_cin;
    
    //赋值
    while (getline(ss, str, '#')){
        result.push_back(str);
    }

    cout<<"迭代器遍历:"<<endl;
    //定义一个迭代器
    vector<string>::iterator iter;
    for(iter = result.begin(); iter != result.end(); iter++){

        for(vector<string>::size_type sty=0; sty!=(*iter).size(); ++sty){

            cout<<(*iter)[sty]<<endl;//cout<<iter1[sty]<<endl;//应先通过迭代器寻址再使用[]算符
        }
    }

    system("pause");
    return 0;
}

二次迭代得到的结果为:

o
n
e
t
w
o
t
h
r
e
e

再或者:

int main(){
	string str="nice to meet you";
	stringstream stream(str);
	string s;
    
	while(stream>>s){
		cout<<s<<endl;
	}
	return 0;
}

输出:

nice
to
meet
you

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值