用strtok函数,其函数声明为
char *strtok( char *strToken, const char *strDelimit );
在C++中应该有更好的方法,比如MFC中CString类中的成员函数SpanExcluding和SpanIncluding都能达到截取字符串的作用。
下面主要介绍strtok。strtok,SpanExcluding和SpanIncluding都可以在MSDN中找到详细的应用方法
参数
strToken String containing token(s)
-
strDelimit
Set of delimiter characters
- 返回值说明
- All of these functions return a pointer to the next token found in strToken . They return NULL when no more tokens are found. Each call modifies strToken by substituting a NULL character for each delimiter that is encountered.
- 例子如下:
Example
/* STRTOK.C: In this program, a loop uses strtok * to print all the tokens (separated by commas * or blanks) in the string named "string". */ #include <string.h> #include <stdio.h> char string[] = "A string\tof ,,tokens\nand some more tokens"; char seps[] = " ,\t\n"; char *token; void main( void ) { printf( "%s\n\nTokens:\n", string ); /* Establish string and get the first token: */ token = strtok( string, seps ); while( token != NULL ) { /* While there are tokens in "string" */ printf( " %s\n", token ); /* Get next token: */ token = strtok( NULL, seps ); } }
Output
A string of ,,tokens and some more tokens Tokens: A string of tokens and some more tokens