[Algorithm] c++ split 함수 구현

Updated:

  • C++에는 문자열을 split 하는 메서드가 따로 없어 직접 구현해야함
  • 필요한 헤더 : vector, sstream

method implementation

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

using namespace std;

vector<string> split(string str, char delimiter);

int main(){
    string test = "This is string.";
    vector<string> result = split(test, ' ');
    for (int i=0;i<result.size();i++){
        cout << result[i] << " ";
    }
}

vector<string> split(string input, char delimiter) {
    vector<string> answer;
    stringstream ss(input);
    string temp;
 
    while (getline(ss, temp, delimiter)) {
        answer.push_back(temp);
    }
 
    return answer;
}

ref :
stackoverflow

Categories:

Updated:

Leave a comment