编程语言
首页 > 编程语言> > 【C++基础】stringstream

【C++基础】stringstream

作者:互联网

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;
}

在这里插入图片描述

标签:word,string,基础,C++,plus,str,stringstream,include
来源: https://blog.csdn.net/m0_47902113/article/details/121877876