[ C++ ] 문자열 파싱 - stringstream, istringstream, ostringstream

반영서·2023년 1월 12일
0

C / C++

목록 보기
4/5
post-thumbnail
  1. istringstream

    • 문자열 format을 파싱할 때 사용한다.
  2. ostringstream

    • 문자열 format을 조합하여 저장할 때 사용한다.
  3. stringstream

    • 문자열에서 원하는 자료형의 데이터를 추출할 때 사용한다.


필요헤더: <sstream>

istringstream

#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;
}



stringstream: 공백 기준 분리

#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
	*/
}

stringstream: 특정 문자 기준 분리

#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
	*/
}



ostringstream

문자열을 붙일 때 사용된다. 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 라이브러리를 정리해봤다.

코딩 테스트에서 문자열 문제는 빠질 수 없는 문제이므로, 종종 사용할 것 같아 기록해본다.

profile
커지고 싶은 신입개발자

0개의 댓글