이 프로그램에서 우리는 C++에서 쉼표로 구분된 문자열을 구문 분석하는 방법을 볼 것입니다. 일부 텍스트가 있는 곳에 문자열을 넣고 쉼표로 구분합니다. 이 프로그램을 실행한 후 해당 문자열을 벡터 유형 개체로 분할합니다.
그것들을 나누기 위해 우리는 getline() 함수를 사용하고 있습니다. 이 함수의 기본 구문은 다음과 같습니다.
getline (input_stream, string, delim)
이 함수는 입력 스트림에서 문자열이나 라인을 읽는 데 사용됩니다.
Input: Some strings "ABC,XYZ,Hello,World,25,C++" Output: Separated string ABC XYZ Hello World 25 C++
알고리즘
Step 1: Create stream from given string Step 2: While the stream is not completed Step 2.1: Take item before comma Step 2.2: Add item into a vector Step 3: Return the vector
예시 코드
#include<iostream>
#include<vector>
#include<sstream>
using namespace std;
main() {
string my_str = "ABC,XYZ,Hello,World,25,C++";
vector<string> result;
stringstream s_stream(my_str); //create string stream from the string
while(s_stream.good()) {
string substr;
getline(s_stream, substr, ','); //get first string delimited by comma
result.push_back(substr);
}
for(int i = 0; i<result.size(); i++) { //print all splitted strings
cout << result.at(i) << endl;
}
} 출력
ABC XYZ Hello World 25 C++