目录
构造函数
输出字符串
修改和清空字符串
利用 stringstream 去除字符串空格
利用stringstream去除指定的字符
stringstream 数据库 <sstream>
构造函数
- 创建一个对象,向对象输入字符串:
string x="abcdefg";
stringstream ss;
ss<<x;
2.字符串初始化(一般用这个方便很多)
string x="abcdefg";
stringstream ss(x);
输出字符串
调用str()函数 str()函数可以将其他类型的数据转换为字符串类型,从而方便我们输出和处理数据
cout<<ss.str()<<endl;
修改和清空字符串
#include<iostream>
#include<sstream>
using namespace std;
int main()
{
string x="abcdefgh";
//初始化
stringstream ss(x);
cout<<ss.str()<<endl;
//修改字符串
ss.str("1234565");
cout<<ss.str()<<endl;
//清空字符串
ss.str(" ");
cout<<ss.str()<<endl;
cout<<"0"<<endl;
return 0;
}
利用 stringstream 去除字符串空格
#include<iostream>
#include<sstream>
using namespace std;
int main()
{
string x="a b c d efg h j";
stringstream ss(x);
string s;
while(ss>>s)
{
cout<<s<<endl;
}
return 0;
}
利用stringstream去除指定的字符
借用getline()函数
#include<iostream>
#include<sstream>
using namespace std;
int main()
{
string x="a, b, c,d,efg,h,j";
stringstream ss(x);
string s;
while(getline(ss,s,','))
{
cout<<s<<endl;
}
return 0;
}
字符串转化成其他类型 int double float
#include<iostream>
#include<sstream>
using namespace std;
int main()
{
string x="12345678";
stringstream ss(x);
int p;
ss>>p;//就想象成读入给p p就有值了
cout<<p<<endl;
cout<<p/2<<endl;
return 0;
}
#include<iostream>
#include<sstream>
using namespace std;
int main()
{
string x="12 34 56 78";
stringstream ss(x);
int p;
while(ss>>p)
{
cout<<p<<endl;
cout<<"*** "<<p/2<<endl;
}
return 0;
}