实现c++中类似php的explode函数
20110316更新:发现自己太土了,居然不知道有strtok 这么一个函数,可以实现类似的功能。 strtok 函数描述如下:(下面英文内容,完全来自于http://www.cplusplus.com/reference/clibrary/cstring/strtok/ ,更多内容和代码示例参加此处)
char * strtok ( char * str, const char * delimiters );
Split string into tokens
A sequence of calls to this function split str into tokens, which are sequences of contiguous characters separated by any of the characters that are part of delimiters.
On a first call, the function expects a C string as argument for str, whose first character is used as the starting location to scan for tokens. In subsequent calls, the function expects a null pointer and uses the position right after the end of last token as the new starting location for scanning.
To determine the beginning and the end of a token, the function first scans from the starting location for the first character not contained in delimiters (which becomes thebeginning of the token). And then scans starting from this beginning of the token for the first character contained in delimiters, which becomes the end of the token.
This end of the token is automatically replaced by a null-character by the function, and the beginning of the token is returned by the function.
Once the terminating null character of str has been found in a call to strtok, all subsequent calls to this function with a null pointer as the first argument return a null pointer.
Parameters
- str
- C string to truncate. The contents of this string are modified and broken into smaller strings (tokens).
Alternativelly, a null pointer may be specified, in which case the function continues scanning where a previous successful call to the function ended. - delimiters
- C string containing the delimiters.
These may vary from one call to another.
Return Value
A pointer to the last token found in string.
A null pointer is returned if there are no tokens left to retrieve.
—————————-我是华丽的分界线—————————————————————
写习惯了php,发现explode很好用,而c++中没有,写了一个。
1 2 3 4 5 6 7 8 9 10 11 12 13 | vector<string> explode(const char * probe, char * data) { string dataStr(data); int pos1 = 0; int pos2 = 0; vector<string> result; while((pos2=dataStr.find(probe,pos1)) != string::npos){ result.push_back(dataStr.substr(pos1,pos2-(pos1+1))); pos1=pos2+1; } result.push_back(dataStr.substr(pos1)); return result; } |
除注明转载的文章外,都是本人原创,转载时请加上原文链接并注明: 转载自品味生活
本文链接地址: 实现c++中类似php的explode函数
Popularity: 12%
最新评论