赞
踩
头文件
#include <sstream>
方法:
构造函数
stringstream
的构造函数有很多,这里列举最为常用的两个构造函数:
两种方式都可以创建对象,但创建后的对象用法不一样。
利用第一种构造函数创建对象时,输入字符串后直接进行字符串拼接,而第二种构造方式,在进行字符串拼接时,首先把原本的字符串覆盖掉,之后再进行拼接。
推荐使用第一种。
输出字符串
stringstream
可以将存储于内部的字符串输出,需要调用 str()
函数,不可直接输出:
std::cout << ss.str() << std::endl;
// std::cout << ss << std::endl; // 错误不可直接输出
数据类型转换
示例:将int
类型转换为string
类型
int main() { stringstream sstream; string str; int n = 100; // 将int类型的值放入输入流中 sstream << n; // 从sstream中抽取前面插入的int类型的值,赋给string类型 sstream >> str; cout << "[cout]str is: " << str << endl; printf("[printf]str is: %s\n", str.c_str()); return 0; } 输出: [cout]str is: 100 [printf]str is: 100
多个字符串拼接
介绍在 stringstream 中存放多个字符串,实现多个字符串拼接的目的(其实完全可以使用 string 类实现),同时,介绍 stringstream 类的清空方法。
int main() { stringstream sstream; // 将多个字符串放入 sstream 中 sstream << "first" << " " << "string,"; sstream << " second string"; cout << "strResult is: " << sstream.str() << endl; // 清空 sstream sstream.str(""); sstream << "third string"; cout << "After clear, strResult is: " << sstream.str() << endl; return 0; } 输出: strResult is: first string, second string After clear, strResult is: third string
利用 stringstream 去除字符串空格
stringstream
默认是以空格来分割字符串的,利用 stringstream
去除字符串空格非常方便:
int main() { stringstream ss("1 abcde 23"); cout << ss.str() << endl; cout<< endl; string str; while (ss >> str) { cout << str << endl; } return 0; } 输出: 1 abcde 23 1 abcde 23
利用 stringstream 指定字符分割字符串
上面描述了利用 stringstream
去除字符串空格,其实就是利用空格来分割字符串,同样,也可以指定其他字符对字符串进行分割,这需要与 getline()
函数搭配使用,下面以逗号分割字符串为例:
int main() { string source = "abc,123,<!>"; stringstream ss(source); cout << ss.str() << endl; cout<< endl; string str; while (getline(ss, str, ',')) { cout << str << endl; } return 0; } 输出: abc,123,<!> abc 123 <!>
打印字符串中单个单词出现的频率
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; } 输出: c->2 hello->1 learning->1 plus->4 word->1
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。