函数原型
用法:#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");
}