C++利用stringstream实现字符串分割和输入
使用stringstream实现字符串转整型
int str2int(string s)
{
stringstream ss;
int n;
ss << s;
ss >> n;
return n;
}
使用stringstream分割字符串
当字符串中含有空格时,或者使用getline函数读取一行字符串后进行按照空格分割成字串时,可以使用stringstream进行分割
string s = "123 456 789";
stringstream sa(s);
vector<int> v;
int word;
while (sa>>word)
{
v.push_back(word);
}
for (int i = 0; i < v.size(); i++)
{
cout << v[i] << endl;
}
配合getline函数实现分割
getline的具体用法参照
getline函数的用法详解
函数实例,对指定字符串以逗号分割
//输入不定长字符串分割
string a = "This,is,a,test";
stringstream aa;
aa << a;
vector<string> vec;
string temp;
while (getline(aa,temp,','))
{
vec.push_back(temp);
}
for (int i = 0; i < vec.size(); i++)
{
cout << vec[i] << endl;
}
对复杂字符串进行处理
//处理字串的分割,取出[]中的数作为数组
string str="asdfa asdfgsdf aasdf[12,45,7,889,789]";
//getline(cin, str);
stringstream ss(str);
vector<string> vecs;
string temp1;
while (getline(ss, temp1, ','))
{
vecs.push_back(temp1);
}
stringstream sts;
for (int i = 0; i < vecs[0].size(); i++)
{
if (vecs[0][i] == '[')//处理第一个数组元素,删除前缀
{
for (int j = i+1; j < vecs[0].size(); j ++)
{
sts << vecs[0][j];
}
break;
}
}
//处理最后一个元素的],删除后缀
vecs[vecs.size() - 1].pop_back();
sts >> vecs[0];
for (int i = 0; i < vecs.size(); i++)
{
cout << vecs[i] << endl;
}
使用strtok进行字符串多个分割符分割
void test10()
{
char str[] = "I,am,a,student; hello world!";
const char *split = ",; !";//使用, 和 ; 和 !三种分割符进行分割
char *p2 = strtok(str,split);
while( p2 != NULL )
{
cout<<p2<<endl;
p2 = strtok(NULL,split);
}
}
关于strtok的用法可以参考strtok()函数详解!