stringstream头文件#include <sstream>
1.构造函数
(1).创建一个对象,向对象输入字符串:
stringstream ss;
ss << str;
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
stringstream ss1;
ss1 << "emxs";
ss1 << "abc";
cout << ss1.str() << endl; //输出:emxsabc
return 0;
}
(2).在创建对象的时候使用字符串初始化:
streamstring ss(str);
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
string str("asd");
stringstream ss2(str);
cout << ss2.str() << endl; //输出:asd
ss2 << "r";
cout << ss2.str() << endl; //输出:rsd
ss2 << "13";
cout << ss2.str() << endl; //输出:r13
ss2 << "hy";
cout << ss2.str() << endl; //输出:r13hy
return 0;
}
利用第一种构造函数创建对象时,输入字符串后直接进行字符串拼接,而第二种构造方式,在进行字符串拼接时,首先把原本的字符串覆盖掉,之后再进行拼接。
(3)如果不想原来的字符串被覆盖,则需要换一种构造方式:
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
ostringstream ss("1 2 3 4 ", std::ios_base::ate); // append 方式追加
cout << ss.str() << endl; //输出:1 2 3 4
ss << "5 3 4";
cout << ss.str() << endl; //输出:1 2 3 4 5 3 4
return 0;
}
2.输出字符串
stringstream
可以将存储于内部的字符串输出,需要调用 str()
函数,不可直接输出
cout << ss.str() << endl;
// cout << ss << endl; // 错误不可直接输出
3.修改,清空stringstream内容
清空 stringstream 有两种方法:clear() 方法以及 str("") 方法。如果想清空 stringstream,使用 str("") 的方式;clear() 方法适用于进行多次数据类型转换的场景。
通过 str() 函数进行修改、清空:
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
stringstream ss("emxs");
cout << ss.str() << endl; //输出:emxs
// 修改内容
ss.str("123456");
cout << ss.str() << endl; //输出:123456
// 清空内容
ss.str("");
cout << ss.str() << endl; //输出:
return 0;
}
4.利用 stringstream 去除字符串空格
stringstream
默认是以空格来分割字符串的
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
stringstream ss("5 emxs 43");
cout << ss.str() << endl;
cout<< endl;
string str;
while (ss >> str)
{
cout << str << endl;
}
return 0;
}
/*
输出:
5 emxs 43
5
emxs
43
*/
5.利用 stringstream 指定字符分割字符串(getline()函数)
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
string source = "emxs,123,<!>";
stringstream ss(source);
cout << ss.str() << endl;
cout<< endl;
string str;
while (getline(ss, str, ',')) //以逗号分割
{
cout << str << endl;
}
return 0;
}
/*
输出:
emxs,123,<!>
emxs
123
<!>
*/
6.例题
单词数
题目描述
统计一篇文章里不同单词的总数。
输入
有多组数据,每组一行,每组就是一篇小文章。每篇小文章都是由小写字母和空格组成,没有标点符号,遇到#时表示输入结束。
输出
每组只输出一个整数,其单独成行,该整数代表一篇文章里不同单词的总数。
样例输入 Copy
you are my friend #
样例输出 Copy
4
AC代码:
#include <iostream>
#include <algorithm>
#include <sstream>
#include <set>
#include <cstring>
using namespace std;
set<string>s1;
int main()
{
string s,str;
while(getline(cin,s),s!="#")
{
stringstream ss(s); //将s的数据传入s缓冲区
while(ss>>str) //ss不为空
{
s1.insert(str);
}
cout<<s1.size()<<endl;
s1.clear(); //清空缓冲区
}
return 0;
}