C++ - Stringstream
2022. 8. 23. 00:28ㆍSTUDY/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<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 = "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
반응형
'STUDY > C++' 카테고리의 다른 글
unordered_map vs map in C++ (2) | 2022.08.22 |
---|---|
C++ min , max, index 구하기 (1) | 2022.08.21 |
C++ - 2차배열 / 동적할당 패턴 연습 (+입력 정리, vector 인자로 넘길때) (0) | 2022.08.19 |
(C++) vector - accumulate, clear/erase, unique(+sort) (0) | 2022.08.18 |
C++ - vector of pairs / vector of vectors (1) | 2022.08.09 |