【C++基础】stringstream

本文介绍了如何利用C++中的stringstream进行字符串处理,包括计算字符串中的单词个数和统计每个单词的出现频率。通过示例代码展示了stringstream的运算符<<和>>的使用,以及如何结合map数据结构实现单词频率统计。

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

stringstream 将字符串对象与流相关联,允许从字符串中读取,有点类似cin
方法:

  1. 运算符 << :将字符串添加到 stringstream 对象;
  2. 运算符 >> :从 stringstream 对象中读取内容;
  3. stringstream(const string& str):用 str 构造一个 stringstream 对象,

应用场景:

  1. 计算字符串中的单词个数:
    输入:“hello world c plus plus”
    输出:5
#include <iostream>
#include <sstream>
#include <string>

using namespace std;

int main() {
	string str = "hello world c plus plus";
	int count = 0;
	stringstream ss(str);
	string word;
	while (ss >> word)
		count++;
	cout << count << endl;

	system("pause");
	return 0;
}

2.打印字符串中单个单词出现的频率
输入:“hello word c plus plus learning c plus plus”
输出:hello-1
world-1
c-2
plus-4
learning-1

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

int main() {
	string str = "hello word c plus plus learning c plus plus";
	int count = 0;
	map<string, int> freq;
	stringstream ss(str);
	string word;
	while (ss >> word)
		freq[word]++;
	
	for (auto it = freq.begin(); it != freq.end(); ++it) {
		cout << it->first << "->" << it->second << endl;
	}

	system("pause");
	return 0;
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值