istringstream
ostringstream
stringstream
필요헤더: <sstream>
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main() {
istringstream iss("test1 123 aaa 456");
int integer1, integer2;
string str1, str2;
// 공백을 기준으로 문자열을 parsing, 변수 형식에 맞게 변환
iss >> str1 >> integer1 >> str2 >> integer2;
}
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main() {
string str = "123 456 789\nTest", token;
stringstream ss(str);
while (ss >> token) {
cout << token << endl;
}
/*
출력값:
123
456
789
Test
*/
}
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main() {
string str = "010-1234-5678", token;
stringstream ss(str);
while (getline(ss, token, '-')) {
cout << token << endl;
}
/*
출력값:
010
1234
5678
*/
}
문자열을 붙일 때 사용된다. int 자료형의 변수도 string으로 type casting 후 붙일 수 있음.
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main() {
ostringstream oss;
string str1 = "Hello", str2 = "C++";
int int1 = 123;
oss << str1 << " " << str2 << "\n" << int1; // 문자열 조립
cout << oss.str() << endl; // str() : 조립된 문자열 반환.
/*
출력값:
Hello C++
123
*/
}
다양한 문자열 parsing 라이브러리를 정리해봤다.
코딩 테스트에서 문자열 문제는 빠질 수 없는 문제이므로, 종종 사용할 것 같아 기록해본다.