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.
a first call: ptr = strtok( str, " " );
In subsequent calls: ptr = strtok( NULL , " " );
/*************************************************
* *
* example of strtok() *
* *
* *
* ************************************************/
#include <string.h>
#include <stdio.h>
int main()
{
char str[] = "mao zhe dong";
char *ptr;
ptr = strtok( str, " " );
puts( ptr );
while( ptr != NULL )
{ printf( " The ptr pointer is at %d \n" , ptr-str+1 );
ptr = strtok( NULL , " " );
if(ptr != NULL) puts( ptr );//---------------
}
return 0;
}
|
输出:
mao
The ptr pointer is at 1
zhe
The ptr pointer is at 5
dong
The ptr pointer is at 9
|
但语句:
if(ptr != NULL) puts( ptr );//---------------
中去掉
if(ptr != NULL)
则输出是:
mao
The ptr pointer is at 1
zhe
The ptr pointer is at 5
dong
The ptr pointer is at 9
Segmentation fault (core dumped)
|
Segmentation fault (core dumped) 这一句不知为什么会出现,原因何在?
-------------
阅读(1047) | 评论(0) | 转发(0) |