關於stroke函式的使用
在程式設計過程中,有時需要對字串進行分割.而有效使用這些字串分隔函式將會給我們帶來很多的便利.
下面我將在MSDN中學到的strtok函式做如下翻譯.
strtok :在一個字串查詢下一個符號
char *strtok( char *strToken, const char *strDelimit );
返回值:返回指向在strToken字串找到的下一個符號的指標,當在字串找不到符號時,將返回NULL.每
次呼叫都通過用NULL字元替代在strToken字串遇到的分隔符來修改strToken字串.
引數:
strToken:包含符號的字串
strDelimit:分隔符集合
注:第一次呼叫strtok函式時,這個函式將忽略間距分隔符並返回指向在strToken字串找到的第一個符
號的指標,該符號後以NULL字元結尾.通過呼叫一系列的strtok函式,更多的符號將從strToken字串中分
離出來.每次呼叫strtok函式時,都將通過在找到的符號後插入一個NULL字元來修改strToken字串.為了
讀取strToken中的下一個符號,呼叫strtok函式時strToken引數為NULL,這會引發strtok函式在已修改過
的strToken字串查詢下一個符號.
Example(摘自MSDN)
/* 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