strtok介绍及用法

函数原型

在这里插入图片描述
用法:#include <string.h> 功能:分解字符串为一组标记串。s为要分解的字符串,delim为分隔符字符串。 说明:首次调用时,s必须指向要分解的字符串,随后调用要把s设成NULL。 strtok在s中查找包含在delim中的字符并用NULL(‘\0’)来替换,直到找遍整个字符串。 返回指向下一个标记串。当没有标记串时则返回空字符NULL。

写法一

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

void func01()
{
	char buf[1024] = "刘备:关羽:张飞:赵云:吕布:诸葛亮";

	char* names[64] = { 0 }; // 将buf中的信息按照:进行分割,放放到字符串数组names中

	int i = 0;
	names[i] = strtok(buf, ":");

	while (names[i] != NULL)
	{
		i++;
		names[i] = strtok(NULL, ":");
	
	}
	// 打印数组
	i = 0;
	while (names[i] != NULL) 
	{
		printf("%s\n",names[i++]);
	
	}

	printf("%s\n",names[i]);
}
int main()
{

	func01();
	return 0;
	system("pause");
}

写法二 —>(代码优化)

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

void func02()
{
	char buf[1024] = "刘备:关羽:张飞:赵云:吕布:诸葛亮:曹操";

	char* names[64] = { buf,NULL }; // 将buf中的信息按照:进行分割,放放到字符串数组names中

	int i = 0;

	while ((names[i++] = strtok(names[i], ":")) != NULL)
	{
		
	}
	
	// 打印数组
	i = 0;
	while (names[i] != NULL)
	{
		printf("%s\n", names[i++]);

	}

}

int main()
{

	func02();
	
	return 0;
	system("pause");
}

写法三 —> (扩展)

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

void func03()
{
	char buf[1024] = "刘备:关羽!张飞%赵云****吕布@诸葛亮:曹操";

	char* names[64] = { buf,NULL }; // 将buf中的信息按照:进行分割,放放到字符串数组names中

	int i = 0;

	while ((names[i++] = strtok(names[i], ":!%*@")) != NULL)
	{

	}

	// 打印数组
	i = 0;
	while (names[i] != NULL)
	{
		printf("%s\n", names[i++]);

	}


}

int main()
{

	func03();
	
	return 0;
	system("pause");
}

执行结果

在这里插入图片描述

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值