자료 저장소

# split 함수

이 예제에서는 표준 알고리즘을 이용하여 작성되었으면 find_if가 사용되었다.
find_if는 세개의 인수를 받으며 처음 두 인자는 시퀀스를 나타내는 반복자들이고, 세번째 인자는 동작함수로서 해당 인자를
검사하여 true나 false를 리턴한다. find_if는 그 시퀀스의 모든 요소들에 대해 그 동작함수를 호출하며, 동작함수가 true의 결과를
내는 요소를 찾아 멈춘다.

isspace 함수는 문자가 공백인지를 검사한다.

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

usingstd::vector;
usingstd::string;
usingstd::find_if;
usingstd::cout;
usingstd::endl;

/* 인자가 공백문자이면 true, 그렇지 않다면 false를 리턴 */
bool space(char c)
{
return isspace(c);
}

/* 인자가 공백문자이면 false, 그렇지 않다면 ture를 리턴 */
bool not_space(char c)
{
return !isspace(c);
}

vector<string> split(conststring& str)
{
typedefstring::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;
}

int main()
{
vector<string> str;
str=split("welcome to programming world!");

for(vector<string>::const_iterator iter=str.begin(); iter!=str.end(); ++iter)
cout<<(*iter)<<endl;

return0;
}
댓글 로드 중…

최근에 게시된 글