strtok函数的用法

strtok函数的用法

介绍

strtok作用是为了分解字符串的,库函数中,原型是

char* strtok(char str[], const char* delim);

str [ ]指要被分解的字符串,delim指字符串中用来分解的字符,该函数返回分解后的字符串的起始位置指针。

代码

#define _CRT_SECURE_NO_WARNINGS 1

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
	char p[] = "abc.def@bc_eg.";
	printf("%s\n", strtok(p, "@._"));
	printf("%s\n", strtok(NULL, "@._"));
	printf("%s\n", strtok(NULL, "@._"));
	printf("%s\n", strtok(NULL, "@._"));
	


	system("pause");
	return 0;
}

截图
在这里插入图片描述

上面代码有点麻烦,可以精简为
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
	char p[] = "abc.def@bc_eg.";
	const char* sep = "_.@";
	char* b;
    b = strtok(p, sep);
	while (b != NULL)
	{
		printf("%s\n", b);
		b = strtok(NULL, sep);
	}
	system("pause");
	return 0;
}

在这里插入图片描述

发布了29 篇原创文章 · 获赞 12 · 访问量 1133

猜你喜欢

转载自blog.csdn.net/childemao/article/details/91050124