C++ - Stringstream

2022. 8. 23. 00:28STUDY/C++

반응형

The stringstream class is extremly useful in parsing input.

To use stringstream, we need to include sstream header file.

StringStream 은, 공백과 \n 을 제외한 문자열을 빼내는데 유용함. 

<<  : Add a string to the stringstream object.

>> : Read something from the stringstream object.

예제 1.

geeks for geeks geeks 를 space 로 나눈 count 값 ! 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// Example program
#include <iostream>
 
#include <sstream>
#include <string>
using namespace std;
 
int countWords(string str) {
    int cnt = 0;
    
    // Used for breaking words
    stringstream s(str);
    string word;
    
    while( s >> word ) cnt++;
        
    return cnt;
}
 
int main()
{
    string s = "geeks for geeks geeks";
    cout << countWords(s);
    
    return 0;
}
 
cs

 

예제 2.

parsing한 string을 map 에 매치 !

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// Example program
#include <iostream>
 
#include <sstream>
#include <string>
#include <map>
using namespace std;
 
void printFrequency(string st)
{
    map<stringint>FW;
    stringstream ss(st);
    string Word;
    
    while(ss >> Word) FW[Word]++;
    
    map<stringint>::iterator m;
    for( m = FW.begin(); m !=FW.end(); m++)
        cout << m->first << "-> " << m->second << '\n';
}
 
int main()
{
    string s = "Geeks For Geeks Ide";
    printFrequency(s);
    
    return 0;
}
 
cs

# 결과 

++++

추가로 ! 입력받은 문자열에서 빈칸'만' 제거하는 방법 ! 

INPUT : g   eeks  for   ge   eeks    "

OUTPUT : geeksforgeeeks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// Example program
#include <iostream>
 
#include <sstream>
#include <string>
#include <map>
using namespace std;
 
string removeSpaces(string str)
{
    str.erase(remove(str.begin(), str.end(), ' '), str.end());
    return str;
}
 
int main()
{
    string str = "g   eeks  for   ge   eeks    ";
    str = removeSpaces(str);
    cout << str;
    
    return 0;
}
 
cs

 

 

728x90
반응형