본문 바로가기

C++

[C++] 문자열(string)을 특정 문자로 자르기

문자열을 sstream을 사용하여 특정 문자열로 구분하여 자르기

 

 

아래 코드는 공백 문자를 기준으로 자르는 방법

#include <string>
#include <vector>
#include <sstream>

using namespace std;

int main() {
    string fruit = "apple lemon grape melon";
    istringstream ss(fruit);
    vector <string> words;
    string word;

    while (getline(ss, word, ' ')) //공백 단위로 구분
        words.push_back(word);

    //words에는 apple, lemon, grape, melon이 저장됨

}

 

 

 

LIST

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

자동 정렬되는 STL (Map vs Set)  (0) 2021.08.30
[C++] 멀티스레드 프로그래밍  (0) 2021.02.25
[C++] STL 정리 - map  (0) 2021.01.15
[C++] STL 정리 - vector  (0) 2021.01.14