본문 바로가기
개발/C++

[C++] String 공백 분리

by parkkingcar 2023. 5. 18.

C++  STL sstream을 사용하여 문자열의 공백을 기준으로 분리합니다.

 

 

공백을 기준으로 분리한 후 변수에 저장, vector에 저장

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

using namespace std;

int main(){

    // 공백 분리할 문자열 선언
    string str = "aaa bb c";

    // 문자열을 스트림화
    stringstream ss(str);
    
    string word;
    vector<string> words;
    
    // 스트림을 통해, 문자열을 공백 분리해 vector에 할당
    while (getline(ss, word, ' ')) {
        words.push_back(word);
    }
    cout << words;
    return 0;
}


// 출력 

// ["aaa", "bb", "c"]

 

 

'개발 > C++' 카테고리의 다른 글

C++ String 사용할 때, 시간복잡도 줄이는 법  (1) 2023.07.13
[C++] 우선순위 큐(Priority Queue)  (0) 2022.12.02

댓글