C++ 程式設計中的 Stringstream
此示例草案計算特定字串中的單詞總數,並使用 C++ 程式設計程式碼中的 stringstream 統計特定單詞的總出現次數。stringstream 類將 string 物件與 stream 結合在一起,使你可以像對待 stream 一樣瀏覽 string。此程式碼將完成兩種操作,首先,它將計算單詞總數,然後使用 map 迭代器基本方法按順序計算字串中各個單詞的頻率,如下所示:
示例
#include <bits/stdc++.h>
using namespace std;
int totalWords(string str){
stringstream s(str);
string word;
int count = 0;
while (s >> word)
count++;
return count;
}
void countFrequency(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";
}
int main(){
string s = "Ajay Tutorial Plus, Ajay author";
cout << "Total Number of Words=" << totalWords(s)<<endl;
countFrequency(s);
return 0;
}輸出
當為本程式提供字串“Ajay Tutorial Plus,Ajay author”時,輸出中的單詞總數和頻率如下所示;
Enter a Total Number of Words=5 Ajay=2 Tutorial=1 Plus,=1 Author=1
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP