stringstream は、文字列オブジェクトをストリームに関連付け、ストリーム (cin など) であるかのように文字列を読み取ることができるようにします。 stringstream を使用するには、以下を含める必要があります ストリーム ヘッダファイル。 stringstream クラスは、入力の解析に非常に役立ちます。
基本的な方法は次のとおりです。
- clear() - ストリームをクリアします。 str() - ストリーム内にコンテンツが存在する文字列オブジェクトを取得および設定します。 演算子 <<- stringstream オブジェクトに文字列を追加します。 演算子>>- stringstream オブジェクトから何かを読み取ります。
例:
1. 文字列内の単語数を数える
例:
入力: アシプ・パワン・クマール
出力: 3入力: オタクのためのオタク
出力: 4
以下は、上記のアプローチを実装するための C++ プログラムです。
C++
// C++ program to count words in> // a string using stringstream.> #include> #include> #include> using> namespace> std;> int> countWords(string str)> {> >// Breaking input into word> >// using string stream> > >// Used for breaking words> >stringstream s(str);> > >// To store individual words> >string word;> >int> count = 0;> >while> (s>> 単語)>>'> >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>
時間計算量: O(n*log(n))。
補助スペース: の上)。
2. 文字列内の個々の単語の頻度を出力する
Javaにはないランダム
例:
入力: オタクのためのオタク クイズ オタク クイズ 練習 練習
出力: の場合 -> 1
オタク -> 3
練習 -> 2
クイズ -> 2入力: 単語文字列の頻度文字列
出力: 頻度 -> 1
文字列 -> 2
単語 -> 1
以下は、上記のアプローチを実装するための C++ プログラムです。
C++
// C++ 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> >mapint>FW; // 単語の区切りに使用 stringstream ss(st); // 個々の単語を保存するには string Word; while (ss>> Word) FW[Word]++; for (auto m : FW) cout<< m.first << '->'<< m.second << '
'; } // Driver code int main() { string s = 'Geeks For Geeks Ide'; printFrequency(s); return 0; }> |
>
>出力
For->1 オタク -> 2 井出 -> 1>>
時間計算量: O(n*log(n))。
補助スペース: の上)。
3. 整数を文字列に変換する
それ以来、文字列ストリームの挿入演算子と抽出演算子はさまざまなデータ型で動作します。これが、整数でうまく機能する理由です。
整数を文字列ストリームに挿入し、それを文字列に抽出した後、その整数値は文字列になります。
コード-
アメリカ合衆国には都市がいくつありますか
C++
// C++ program to demonstrate the> // use of a stringstream to> // convert int to string> #include> #include> using> namespace> std;> // Driver code> int> main()> {> >int> val=123;> >// object from the class stringstream> >stringstream geek;> >// inserting integer val in geek stream> >geek << val;> >// The object has the value 123> >// and stream it to the string x> >string x;> >geek>> x;>> >// Now the string x holds the> >// value 123> >cout<'4'< return 0; }> |
>
>出力
1234>
時間計算量: O(n) ,n は整数の長さです
補助スペース:O(n)
Stringstream を使用して文字列からスペースを削除する
C/C++ での文字列から数値への変換