stringstream将字符串对象与流相关联,使您可以从字符串读取内容,就好像它是流一样(如cin)。
基本方法是–
clear() — to clear the stream
str() — to get and set string object whose content is present in stream.
operator << — add a string to the stringstream object.
operator >> — read something from the stringstream object,
stringstream类在解析输入时非常有用。
应用范围:
- 计算字符串的单词数
Examples: Input : Asipu Pawan Kumar Output : 3 Input : Geeks For Geeks Ide Output : 4
// CPP program to count words in a string // using stringstream. #include
using namespace std; int countWords(string str) { // breaking input into word using string stream stringstream s(str); // Used for breaking words string word; // to store individual words int count = 0; while (s >> word) count++; return count; } // Driver code int main() { string s = "geeks for geeks geeks " "contribution placements"; cout << " Number of words are: " << countWords(s); return 0; } 输出:
Number of words are: 6
- 打印字符串中单个单词的频率
Input : Geeks For Geeks Quiz Geeks Quiz Practice Practice Output : For -> 1 Geeks -> 3 Practice -> 2 Quiz -> 2 Input : Word String Frequency String Output : Frequency -> 1 String -> 2 Word -> 1
// CPP program to demonstrate use of stringstream // to count frequencies of words. #include
using namespace std; void printFrequency(string st) { // each word it mapped to it's frequency map FW; stringstream ss(st); // Used for breaking words string Word; // To store individual words while (ss >> Word) FW[Word]++; map ::iterator m; for (m = FW.begin(); m != FW.end(); m++) cout << m->first << " -> " << m->second << "\n"; } // Driver code int main() { string s = "Geeks For Geeks Ide"; printFrequency(s); return 0; } 输出:
For -> 1 Geeks -> 2 Ide -> 1
- 使用Stringstream从字符串删除空格
- 在C / C++中将字符串转换为数字
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。