关于strtok()函数的小小的理解

函数原型:

char *strtok(char *str, const char *delim)         分解字符串 str 为一组字符串,delim 为分隔符。

用法:

#include <string.h>
#include <stdio.h>
int main()
{
   const char str[80] = "This is - www.w3cschool.cn - website";
   const char s[2] = "-";
   char *token;
   
   /* 获取第一个子字符串 */
   token = strtok(str, s);
   
   /* 继续获取其他的子字符串 */
   while( token != NULL ) 
   {
      printf( " %s\n", token );
    
      token = strtok(NULL, s);
   }
   
   return(0);
}

在第一次调用函数的时候第一个参数是即将被分割的字符串,第二个参数是分隔符。

返回第一个子字符串的指针(地址)。

接着设置循环,这时第一个参数为NULL(表示这次strtok函数调用将从上一次strtok函数调用保存的位置开始,继续对字符串分割——参照《C语言大学教程第八版》)

-------------------------------动动手脚----------------------------------

#include<stdio.h>
#include<string.h>
#define SIZE 100
int main()
{
	char Word[SIZE];
	gets(Word);

	char* pWord=strtok(Word," ");
	while(pWord!=NULL)
	{
		*(pWord+1)='0';// 1
		printf("%s\n",pWord);
                *(pWord+1)='0';// 2
		pWord=strtok(NULL," ");
                *(pWord+1)='0';// 3
	}

	return 0;
}

这是一个分割字符的程序。我在while循环里加了一行:
*(pWord+1)='0';

当我加在标号1位置时,pWord指针应该指向第一个子字符串,所以果不其然输出的结果每一个子字符的第二个字符都被换成0。

当我加在标号2位置时,pWord指针还应该指向第一个子字符串,由于第一个子字符串已经被打印,接着pWord又被赋成第二个子字符串,所以最终打出来的结果并没有改变。

当我加在标号3位置时,该操作从第二个子字符串开始执行,当执行到最后一个子字符串时(最后一个循环时),执行到该

*(pWord+1)='0';操作时,pWord=NULL,所以程序会报错:找不到地址。

猜你喜欢

转载自blog.csdn.net/LOG_IN_ME/article/details/79387045