C++中的stringstream的使用例子

本文主要记录stringstream的简单使用例子。

计算string中单词的个数

int countWords (string str){
    stringstream s(str);
    string word;
    int count = 0;
    while (s>>word)
        count++;
    return count;
}

计算string中每个单词出现的个数

void printFrequency(string st)
{
    map<string,int> FW;
    stringstream ss(st);
    string Word;
    while(ss>> Word)
        FW[Word]++;
    map<string, int>::iterator m;
    for (m = FW.begin(); m!=FW.end(); m++)
        cout<<m->first<<" ->"<< m->second <<" \n";
}

删除字符串中的空格

string removeSpaces(string str)
{
    stringstream ss;
    string temp;
    // storing the whole string into string stream
    ss<<str;
    str = "";
    while (!ss.eof()){
        //extracting word by word from stream
        ss>>temp;
        // concatenating in the string to be returned
        str = str+temp;
    }
    return str;
}

将string转换成为数字

int convertToInt(string str)
{
    stringstream ss(str);
    int x;
    ss>>x;
    return x;
}

整体的验证代码

int countWords (string str){
    stringstream s(str);
    string word;

    int count = 0;
    while (s>>word)
        count++;
    return count;
}
void printFrequency(string st)
{
    map<string,int> FW;
    stringstream ss(st);
    string Word;
    while(ss>> Word)
        FW[Word]++;
    map<string, int>::iterator m;
    for (m = FW.begin(); m!=FW.end(); m++)
        cout<<m->first<<" ->"<< m->second <<" \n";
}

string removeSpaces(string str)
{
    stringstream ss;
    string temp;
    // storing the whole string into string stream
    ss<<str;
    str = "";
    while (!ss.eof()){
        //extracting word by word from stream
        ss>>temp;
        // concatenating in the string to be returned
        str = str+temp;
    }
    return str;
}

int convertToInt(string str)
{
    stringstream ss(str);
    int x;
    ss>>x;
    return x;
}
int main(){
    string s = "This is a simple stringstream demo";
    cout<<s<<endl;
    cout<<"Number of words are: "<<countWords(s)<<std::endl;
    cout<<"The frequency of words in string:"<<endl;
    printFrequency(s);
    cout<<"After removing space in string: ";
    cout<<removeSpaces(s)<<endl;
    cout<<"Coverting string to number:"<<endl;
    s = "12345";
    cout<<"\t current string is: "<<s<<endl;
    cout<< "\t Value of x: "<<convertToInt(s)<<endl;
    return 0;
}

运行结果:
这里写图片描述

【1】参考文献:
[1] stringstream in C++ and its applications

猜你喜欢

转载自blog.csdn.net/u012836279/article/details/80381803