C++에서는 다른 언어(Java,Python, ...)와 다르게 split 함수를 별도로 지원하지 않는다.

그래서 문자열 함수를 통해 직접 split 함수를 구현해서 써야한다.

 

범용 split 함수를 구현해보면 아래와 같이 구현할 수 있다.

text(전체 문자열), delimiter(구분자)를 입력 받아 string 벡터를 출력하는 함수이며, 두 글자 이상의 구분자를 사용할 수 있다.

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

using namespace std;

vector<string> split(string text, string delimiter) {
	vector<string> result;
	size_t previous = 0, current;
    string substring;
    
    current = text.find(delimiter);
    
    while( current != string::npos) {
    	substring = text.substr(previous, current - previous);
        result.push_back(substring);
        previous = current + delimiter.length();
        current = text.find(delimiter, previous);
    }
    substring = text.substr(previous, current - previous);
    result.push_back( substring);
    return result;
}

void main() {
    string as = "this, is, string";
    
    vector<string> as_with_split = split(as, ", ");
    
    for(string each : as_with_split){
    	cout << each << endl;
    }
    vector<int> answer;
    
    return answer;
}
 
 
 
 

+ Recent posts