split
- split 함수는 주로 문자열을 특정 문자열을 기준으로 쪼개어서 배열화 시키는 함수로 사용됩니다. C++의 STL에서는 split 함수를 지원하지 않기 때문에 직접 구현해야 합니다.
Split 구현
#include <iostream>
#include <vector>
using namespace std;
vector<string> Split(string str, string del) {
int pos = 0;
vector<string> arr;
while ((pos = str.find(del)) != string::npos){
string token = str.substr(0,pos);
arr.push_back(token);
str.erase(0, pos + del.size());
}
if (str != "") {
arr.push_back(str);
}
return arr;
}
int main()
{
auto v = Split("a,b,c,d,", ",");
for (auto value : v) {
cout << value << " ";
}
return 1;
}
- string::npos는 string.find() 함수를 이용해서 원하는 문자열을 찾기에 실패할 경우 return 하는 상수입니다.