상세 컨텐츠

본문 제목

c++ : sstream, string split

공부/c++

by 움바둠바 2024. 7. 25. 15:05

본문

728x90

== string stream!!

 

<sstream> 헤더파일을 추가해서 사용할 수 있다.

string을 다루기 위한 stream이라고 생각하면 될것같다.

 

1. iostream을 상속받음

-> 즉 iostream의 각종 메서드를 사용할 수 있다.

 

2. 문자열 split 가능

sstream은 문자열에서 공백 (스페이스, 줄바꿈)을 만나면 >>, << 연산자를 통해 배출된다.

"I am happy" 라는 문자열을 sstream객체에 넣어주면, (ss라는 객체라 생각)

ss >> temp; 를 통해 temp에는 I가 들어가게된다.

다시한번 ss >> temp를 하게되면, 이번에는 am이 들어가고

ss >> temp를 또 하면 happy가 들어가게된다.

 

이걸 이용해서 문자열 자르기를 할 수 있다!

주의할점 : 띄어쓰기 기준으로 잘려서, 띄어쓰기는 전부 날아가게된다.

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

using namespace std;

int main(){
    string str = "Hello world i am happy";
    stringstream ss(str);
    string temp;

    cout << "test1 : "<<str<<endl;
    while(ss >> temp){
        cout << temp << endl;
    }

    cout << endl;
    string str2 = "Hello world           i am happy";
    stringstream ss2(str2);
    string temp2;

    cout << "test2 : "<<str2<<endl;
    while(ss2 >> temp2){
        cout << temp2 << endl;
    }


    return 0;
}

 

2-1. temp를 원하는 형식으로 받을 수 있음

temp가 int형이면, 문자열 중 int가 되는 부분만 가져와준다.

 

3. split 기준자 설정 가능

getline을 이용한다.

getline(스트림, split한 문자열을 담을 변수, 기준 char)

로 사용한다.

이 때 기준자는 char형만 가능하다.

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

using namespace std;

int main(){
    string str = "Hello world i am happy really realll lei ld";
    stringstream ss(str);
    string temp;

    while(getline(ss, temp, 'l')){
        cout << temp << endl;
    }


    return 0;
}

 

 

4. get, unget

커서 움직임처럼 이용할 수 있다.

get : 커서를 뒤로 움직임 (값 반환) : 아스키코드값으로 나옴 주의

unget : 커서를 앞으로 움직임 (>> 이용 후, ss.unget();을 해주면 다시 앞으로 이동!)

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

using namespace std;

int main(){
    string str = "Hello world i am happy";
    stringstream ss(str);
    char temp;

    cout << ss.get() << endl;
    cout << (char)ss.get() << endl;
    cout << (char)ss.get() << endl;
    cout << (char)ss.get() << endl;
    cout << (char)ss.get() << endl;

    ss.unget();
    ss.unget();
    ss.unget();
    cout << (char)ss.get() << endl;

    return 0;
}

char로 변경해주지 않으면, 아스키코드 숫자로 나온다.

728x90

관련글 더보기