programming language/c++

[C++] 공백, 특정 문자(:/,-..) 기준 문자열 자르기

그린푸딩 2022. 11. 26. 16:58
728x90
반응형

코테에서 문자열 다루는 문제에서 자주 쓰일수 있는 방법이다. 

 

 

 

<공백 기준 문자열 자르기> 

 

sstream 라이브러리에 있는 "stringstream"을 사용한다. 

#include<sstream> 
#include<iostream>

using namespace std;

int main(){

  string s="Hello World!";
  
  stringstream ss(s); 
  ss.str(s); 
  
  string spit_words;
  while(ss>>split_words){
  
      cout<<split_words;   
  }

}

 

<특정 문자열 기준 자르기> 

'-' 기준으로 자른다고 해보면 다음과 같이 getline()과 istringstream을 사용한다.  

#include<string>
#include<sstream>
#include<iostream>

using namespace std;

int main(){


   string times="2022-11-26";
   char separator='-';
   
   istringstream iss(times);
   string str_buf;
   while(getline(iss,str_buf,separator)){
   
       cout<<str_buf; 
       //stoi(str_buf)하면 정수로 사용가능하다.
   }

   //출력결과 
   //20221126
    
}
728x90
반응형