C语言strtok函数用法及案例

在使用strtok函数之前,先添加头文件#include <string.h>
函数的原型为:char * strtok(char *s, const char *delim);
其中:
参数s字符串指针,即分割之前的字符串
参数delim:用于分割的字符串指针,即分割符号
在使用strtok函数时,第一次调用需要给定s参数的值,往后的每一次调用只需将s参数设置为NULL即可。我们通常使用while循环自动分割字符串的所有字符。

参考案例如下:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main()
{
    
    
	char words[100] = "It, is, an, example!\n";  // 待分割前的字符串
	char* Rslt = NULL;  // 定义分割出来的每个字符串
	Rslt = strtok(words, ",");  // 在第一次分割时,需要指定源字符串
	while (Rslt != 0)
	{
    
    
		printf("%s", Rslt);
		Rslt = strtok(NULL, ",");  // 之后的每一次分割只需将第一个参数换成NULL即可
	}
	return 0;
}

输出:
在这里插入图片描述

おすすめ

転載: blog.csdn.net/qq_43511299/article/details/119353013
おすすめ