strtok, strtok_r - delimiter가 2개 이상 연속으로 와도 1개로 처리 (empty field가 불가능)
strsep - delimiter가 2개 이상 오면 각각을 따로 처리 (empty field가 가능)
strtok와 strtok_r의 차이 strtok는 내부의 static 변수를 쓰고 strtok_r은 외부에서 입력한 변수에
현재 상태를 저장하므로 reentrant하다. (당연히 thread safe함)
empty field = string size가 0인 field
split 구현
space와 not_space 함수를 적절히 바꾸어 사용하면 됨.
bool space(char c)
{
return isspace(c);
}
bool not_space(char c)
{
return !isspace(c);
}
vector<string> split(const std::string& str)
{
typedef string::const_iterator iter;
vector<string> ret;
iter i = str.begin();
while (i != str.end()) {
i = find_if(i, str.end(), not_space) ;
// 다음 단어의 끝을 검색
iter j = find_if(i, str.end(), space);
// [i, j)의 문자들을 복사
if (i != str.end())
ret.push_back(string(i,j));
i = j;
}
return ret;
}
strsep - delimiter가 2개 이상 오면 각각을 따로 처리 (empty field가 가능)
strtok와 strtok_r의 차이 strtok는 내부의 static 변수를 쓰고 strtok_r은 외부에서 입력한 변수에
현재 상태를 저장하므로 reentrant하다. (당연히 thread safe함)
empty field = string size가 0인 field
split 구현
space와 not_space 함수를 적절히 바꾸어 사용하면 됨.
bool space(char c)
{
return isspace(c);
}
bool not_space(char c)
{
return !isspace(c);
}
vector<string> split(const std::string& str)
{
typedef string::const_iterator iter;
vector<string> ret;
iter i = str.begin();
while (i != str.end()) {
i = find_if(i, str.end(), not_space) ;
// 다음 단어의 끝을 검색
iter j = find_if(i, str.end(), space);
// [i, j)의 문자들을 복사
if (i != str.end())
ret.push_back(string(i,j));
i = j;
}
return ret;
}