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<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<first<<" ->"<< m->second <<" \n";
}

string removeSpaces(string str)
{
    stringstream ss;
    string temp;
    // storing the whole string into string stream
    ss<"";
    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<cout<<"Number of words are: "<std::endl;
    cout<<"The frequency of words in string:"<cout<<"After removing space in string: ";
    cout<cout<<"Coverting string to number:"<"12345";
    cout<<"\t current string is: "<cout<< "\t Value of x: "<return 0;
}

运行结果:
C++中的stringstream的使用例子_第1张图片

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

你可能感兴趣的:(C++)