在python中,我们可以使用split()函数来分割字符串,在C++中同样可以用sringstream字符串流来实现该功能,并且该sstream还有更丰富的功能,支持接受与返回各种基本类型数据。它将字符串和流关联起来,允许我们像数数据流一样从中读取字符串。
一、头文件
使用时需要包含头文件:sstream
<sstream>库定义了三种类:istringstream、ostringstream和stringstream,分别用来进行流的输入、输出和输入输出操作
#include <sstream>
using namespace std;
int main()
{
stringstream ss;
}
二、成员函数
函数 | 描述 |
---|---|
clear() | to clear the stream(子挨进行多次转换前必须先清除sstream) |
str() | to get and set string object whose content is present in stream |
operator << | add a string to the stringstream object |
operator >> | read somethong from the stringstream object |
三、sstream的应用
基本使用:接收字符串,并以空格分隔字符串
#include <bits/stdc++.h>
using namespace std;
int main()
{
string str = "xxx xxxx xxxxx";
stringstream ss(str);
string word;
while(ss >> word)
{
cout << word << endl;
}
return 0;
}
第七行声明了stringstream对象并初始化,while循环中读取stringstream对象中的字符串并输出,输出:
xxx
xxxx
xxxxx
1、计算一个字符串里面的单词数:
int countWords(string str)
{
stringstream ss(str);
string word;
int count = 0;
while(ss >> word)
{
count++;
}
return count;
}
2、计算字符串中每个单词出现的频率:
void printFrequency(string str)
{
map<string, int> m;
map<string, int>::iterator it;
stringstream ss(str);
string word;
while(ss >> word)
{
m[word]++;
}
for (it=m.begin(); it!=m.end(); it++)
{
cout << it->first << " " << it->second << endl;
}
}
3、删除字符串里面的空格:
string removeSpace(string str)
{
stringstream ss(str);
string word, s = "";
while(ss >> word)
{
s += word;
}
return s;
}
4、反转字符串里面的单词:
void reverseWord(string str)
{
stringstream ss(str);
string word;
while (ss >> word)
{
reverse(word.begin(), word.end());
cout << word;
}
}
5、类型转换:string to int:
int convertToInt(string str)
{
stringstream ss(str);
int x;
ss >> x;
return x;
}
或:使用流插入运算符 << 和 流提取运算符 >>
string res = "123456";
int n = 0;
ss << res;
ss >> n;
6、类型转换:int to string:
int main()
{
stringstream ss;
string s;
int i = 100;
ss << i;
ss >> s;
cout << s;
}
7、实现任意类型的转换:
#include <bits/stdc++.h>
using namespace std;
template <class out_type, class in_type>
out_type convert(const in_type& in)
{
stringstream ss;
ss << in;
out_type out;
ss >> out;
return out;
}
int main()
{
string str = "10";
int n = convert<int>(str); //需要指明返回类型
cout << n+1;
}
完结 cheers! ?