C++ 및 해당 응용 프로그램의 stringstream

stringstream은 문자열 개체를 스트림과 연결하여 마치 스트림(cin과 같은)인 것처럼 문자열에서 읽을 수 있도록 합니다. stringstream을 사용하려면 다음을 포함해야 합니다. 스트림 헤더 파일. stringstream 클래스는 입력을 구문 분석하는 데 매우 유용합니다.

기본 방법은 다음과 같습니다.

    clear()- 스트림을 지웁니다. str()- 콘텐츠가 스트림에 존재하는 문자열 개체를 가져오고 설정합니다. 연산자 < <- stringstream 객체에 문자열을 추가합니다. 연산자>>- stringstream 객체에서 무언가를 읽습니다.

예:

1. 문자열의 단어 수 계산

예:

입력: 아시푸 파완 쿠마르
산출:

입력: 괴짜를 위한 괴짜 Ide
산출: 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>> 단어)> > 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 

시간 복잡도: O(n*log(n)).

보조 공간: 에).

2. 문자열에 있는 개별 단어의 빈도를 인쇄합니다.

예:

입력: Geeks For Geeks 퀴즈 Geeks 퀴즈 연습 연습
산출: -> 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]++; (자동 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++에서 문자열을 숫자로 변환