코딩테스트/공통

C++ stringstream 사용법 (문자열에서 공백 제외 추출, 특정값)

ShovelingLife 2022. 8. 11. 21:48

1) 문자열을 나누는 stringstream

C++에서 stringstream은 주어진 문자열에서 필요한 자료형에 맞는 정보를 꺼낼 때 유용하게 사용된다. stringstream에서 공백과 '\n'을 제외하고 문자열에서 맞는 자료형의 정보를 빼낸다. 

˙ #include <sstream>  전처리 헤더를 필수로 포함해야 한다. 

˙ stream.str(string str) 은 현재 stream의 값을 문자열 str로 바꾼다. 

int num;
string str = "123 456";
stringstream stream; 
stream.str(str);
while(stream1 >> num ) cout << num << endl; 

2) stringstream 초기화

stringstream은 stream.str(""); 구문을 통해 또는 생성자로 초기화 한다. 

int num;
string str = "123 456";
stringstream stream; // stringstream stream(str);
stream.str(str);
while(stream1 >> num ) cout << num << endl;
stream.str("");//초기화

3) stringstream을 활용해 날짜를 초로 바꾸기 

#include <iostream>
#include <sstream>
#include <string>
#include <vector> 
using namespace std;
int main(void){
	
	vector<long long> time;
	string str = "2019:06:30 12:00:30";//연 월 일 시 분 초  
	for(int i=0;i<str.size();i++){
		if(str[i] == ':') 
		str[i] = ' ';
	}
	
	long long num  = 0;
	stringstream stream;
	stream.str(str);
	while(stream >> num){
		time.push_back(num);
	}
	
	long long second = 0;
	second  += time[0] * 365 *  24 * 60 * 60;//연 
	second += time[1] * 30 * 24 * 60 * 60;//월 
	second += time[2] * 24 * 60 * 60;//일 
	second += time[3] * 60 * 60;//시 
	second += time[4] * 60;//분 
	second += time[5];//초 
	
	cout << second << endl; 
	return 0;
}

출처: https://life-with-coding.tistory.com/403 [코딩젤리:티스토리]