C++

문자열 파싱 함수 - istringstream, ostringstream, stringstream

오늘은 2021 카카오 블라인드 문제를 풀며 사용했던 문자열 파싱 함수 세 가지에 대해서 포스팅하려고 한다. 세 함수는 모두 sstream 헤더에 포함되어 있다.

 

1. istringstream

  string을 입력받아 다른 형식으로 바꿔주는 기능을 한다. 예제 코드를 보며 기능을 확인해보자.

 

#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int main() {
	istringstream iss("test 123 aaa 456");
	string s1, s2;
	int i1, i2;
	iss >> s1 >> i1 >> s2 >> i2; // 공백을 기준으로 문자열을 parsing하고, 변수 형식에 맞게 변환

	cout << s1 << endl;
	cout << i1 << endl;
	cout << s2 << endl;
	cout << i2 << endl;
}

 

결과

 

이처럼 istringstream은 공백을 기준으로 문자열을 파싱하여 변수의 형식에 맞게 변환해준다.

 

2. ostringstream

  ostringstream은 string을 조립하거나, 특정 수치를 문자열로 변환하기 위해 사용한다. 마찬가지로 예제를 보며 기능을 확인해보자.

 

#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int main() {
	ostringstream oss;
	string s1 = "abc", s2 = "gjw";
	int i1 = 19234;
	double d1 = 3.591;
	oss << s1 <<"\n"<< i1 <<"\n"<< s2 <<"\n"<< d1; // 문자열 붙이기
	cout << oss.str() << endl; // str() : ostringstream 객체에서 조립된 문자열을 꺼낸다.
}

 

결과

 

ostringstream은 문자열을 붙이는 것 외에도 int나 double형과 같은 수치값을 간단하게 string으로 바꿀 수 있다.

 

3. stringstream

stringstream은 가지고 있는 string에서 공백과 \n을 제외한 문자열을 차례대로 빼내는 역할을 수행한다.

 

#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int main() {
	string str = "123 456 789\nabc\ndef", token;
	stringstream ss(str);
	while (ss >> token) {
		cout << token << endl;
	}
}

 

결과

 

 

만약 공백이나 \n이 아닌 다른 문자를 기준으로 문자열을 분리하고 싶다면 어떻게 해야할까? 이럴 때는 std::getline() 함수를 사용하면 된다.

 

#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int main() {
	string str = "gkg|qiew|789", token;
	stringstream ss(str);
	while (getline(ss, token, '|')) {
		cout << token << endl;
	}
}

 

결과

 

 

 

C++에는 이와 같은 다양한 문자열 파싱 함수들이 존재하며, 이를 사용해 손쉽게 문자열을 다룰 수 있다. 다음에 문자열 관련 문제가 나오면 까먹지 말고 사용해봐야겠다.

'C++' 카테고리의 다른 글

문자 검색 함수 - strchr  (0) 2021.02.11
부분집합 판별 함수 - Includes  (0) 2021.01.12