개발/C++
[C++] String 공백 분리
parkkingcar
2023. 5. 18. 15:43
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"]