Programming - cpueblo.com

stl string 의 explode 구현


글쓴이 : 유광희 날짜 : 2011-01-12 (수) 13:44 조회 : 7950
/* 
explode_token()

string s = "hello_myname_is_kwanghee";
vector  ret = explode_token("_n", s);

ret = hello,my,ame,is,kwa,ghee
*/
vector  explode_token(const tstring& delimiters, const tstring &str)
{
	vector  tokens;
	// Skip delimiters at beginning.
	string::size_type lastPos = str.find_first_not_of(delimiters, 0);
	// Find first "non-delimiter".
	string::size_type pos     = str.find_first_of(delimiters, lastPos);
		while (string::npos != pos || string::npos != lastPos)
	{
		// Found a token, add it to the vector.
		tokens.push_back(str.substr(lastPos, pos - lastPos));
		// Skip delimiters.  Note the "not_of"
		lastPos = str.find_first_not_of(delimiters, pos);
		// Find next "non-delimiter"
		pos = str.find_first_of(delimiters, lastPos);
	}
		return tokens;
}

/*
explode_string()
string s = "hello_myname_is_kwanghee";
vector  ret = explode_token("_k", s);
ret = hello_myname_is,wanghee
*/

vector explode_string(tstring findstr, tstring s)
{
	vector ret;
	int iPos = s.find(findstr, 0);
	int iPit = findstr.length();
	while(iPos > -1) 
	{
		if(iPos != 0)
			ret.push_back(s.substr(0,iPos));
		s.erase(0,iPos+iPit);
		iPos = s.find(findstr, 0);
	} // end while
	if(s != _T("L"))
		ret.push_back(s);
	return ret;
}