본문 바로가기
알고리즘/개념정리

알고리즘(C++) / string 자르기 : stringstream, 문자열 파싱istringstream, ostringstream

by clean_h 2021. 8. 22.
728x90

string 자르기 : stringstream

string을 자르고 싶을 때마다 반복문으로 어느 문자열까지 자르곤 했었는데 그렇지 않고 stringstream을 사용하여 string을 자르는 방법을 알아본다. 

 

stringstream은 string에서 같은 string을 자르기 위해서는 사용되지 않고 자료형에 맞는 문자열을 얻기 위해서 사용된다. 가지고 있는 string에서 공백과 \n을 제외한 문자열을 차례대로 빼내는 역할을 수행한다.

예를 들면 abc 123 def에서 stringstream을 사용하면 abc, 123, def로 다른 자료형(string, int)끼리는 문자열을 자를 수 있지만 ab, c123, def처럼 다른 자료형을 자르기 위해서는 사용되지 않는다. 

 

//stringstream test
#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main() {
	int num;
	string s;
	string str1 = "abc 123 def";
	
	//3개 모두 같은 의미, stream1을 초기화
	stringstream stream1("abc 123 def");
	//stringstream stream1(str1);
	//stream1.str(str1);

	stream1 >> s; //string형에 맞는 string을 찾는다.
	stream1 >> num; //int형에 맞는 string을 찾는다.

	cout << "s : " << s << endl;
	cout << "num : " << num << endl;

	return 0;
}

 

//3개 모두 같은 의미, stream1을 초기화
stringstream stream1("abc 123 def");
stringstream stream1(str1);
stream1.str(str1);

3개 모두 같은 의미로 stream1을 초기화한다. 

 

결과화면

다음과 같이 문자열을 사용할 수 있다.

 

istringstream, ostringstream도 함께 알아본다. 

istringstream

stringstream과 비슷하게  string을 입력받아 다른 형식으로 바꿔주는 기능을 한다. 여러 개의 문자열로 분리할 때 사용할 수 있다. 

//stringstream test
#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main() {
	int num;
	string s1;
	string s2;
	
	//stream1을 초기화
	istringstream stream1("abc 123 def");


	stream1 >> s1 >> num >> s2; //공백을 기준으로 문자열을 나눈다. 

	cout << "s1 : " << s1 << endl;
	cout << "num : " << num << endl;
	cout << "s2 : " << s2 << endl;

	return 0;
}

 

결과

 

ostringstream

반대로 문자열을 조합할 수 있다. 

//stringstream test
#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main() {
	int num = 123;
	string s1 = "abc";
	string s2 = "def";
	
	//stream1을 초기화
	ostringstream stream1;

	stream1 << s1 << " " << num << " " << s2;

	cout << stream1.str() << "\n";

	return 0;
}

 

결과

728x90

댓글