C++ 字符串流的使用

  在python中,我们可以使用split()函数来分割字符串,在C++中同样可以用sringstream字符串流来实现该功能,并且该sstream还有更丰富的功能,支持接受与返回各种基本类型数据。它将字符串和流关联起来,允许我们像数数据流一样从中读取字符串。

一、头文件

使用时需要包含头文件:sstream
<sstream>库定义了三种类:istringstream、ostringstream和stringstream,分别用来进行流的输入、输出和输入输出操作

#include <sstream>
using namespace std;

int main()
{
	stringstream ss;
}


二、成员函数

函数描述
clear()to clear the stream(子挨进行多次转换前必须先清除sstream)
str()to get and set string object whose content is present in stream
operator <<add a string to the stringstream object
operator >>read somethong from the stringstream object


三、sstream的应用

基本使用:接收字符串,并以空格分隔字符串

#include <bits/stdc++.h>
using namespace std;

int main()
{
	string str = "xxx xxxx xxxxx";
	stringstream ss(str);
	string word;
	while(ss >> word)
	{
		cout << word << endl;
	}
	return 0;
}

第七行声明了stringstream对象并初始化,while循环中读取stringstream对象中的字符串并输出,输出:

xxx
xxxx
xxxxx

1、计算一个字符串里面的单词数

int countWords(string str)
{
	stringstream ss(str);
	string word;
	int count = 0;
	while(ss >> word)
	{
		count++;
	}
	return count;
}

2、计算字符串中每个单词出现的频率

void printFrequency(string str)
{
	map<string, int> m;
	map<string, int>::iterator it;
	stringstream ss(str);
	string word;
	while(ss >> word)
	{
		m[word]++;
	}
	for (it=m.begin(); it!=m.end(); it++)
	{
		cout << it->first << " " << it->second << endl;
	}
}

3、删除字符串里面的空格

string removeSpace(string str)
{
	stringstream ss(str);
	string word, s = "";
	while(ss >> word)
	{
		s += word;
	}
	return s;
}

4、反转字符串里面的单词

void reverseWord(string str)
{
	stringstream ss(str);
	string word;
	while (ss >> word)
	{
		reverse(word.begin(), word.end());
		cout << word;
	}
}

5、类型转换:string to int

int convertToInt(string str)
{
	stringstream ss(str);
	int x;
	ss >> x;
	return x;
}

或:使用流插入运算符 << 和 流提取运算符 >>

string res = "123456";
int n = 0;
ss << res;
ss >> n;

6、类型转换:int to string

int main()
{
	stringstream ss;
	string s;
	int i = 100;
	ss << i;
	ss >> s;
	cout << s;
}

7、实现任意类型的转换

#include <bits/stdc++.h>
using namespace std;

template <class out_type, class in_type>
out_type convert(const in_type& in)
{
	stringstream ss;
	ss << in;
	out_type out;
	ss >> out;
	return out;
}

int main()
{
	string str = "10";
	int n = convert<int>(str);  //需要指明返回类型
	cout << n+1;
}

完结 cheers! ?

  • 4
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值