切割字符串是常用的处理。
这里给出一个使用函数strtok切割字符串的例子。
使用C语言的库函数strtok来切割字符串的好处在于,可以指定任意字符作为分隔符来切割单词。使用该函数,切割字符串的分隔符可以同时指定多个,放在一个字符串数组中。
程序中,指定了以空格“ ”、逗号“,”和句号“.”作为分隔符。
程序如下:
/* B00009 C语言分割字符串库函数strtok */
#include <stdio.h>
#include <string.h>
int main(void)
{
char s[]="So, you've never programmed before. As we go through this tutorial,I will attempt to teach you how to program.";
char delim[] = " ,.";
char *p;
p = strtok(s, delim);
while(p) {
printf("%s\n",p);
p = strtok(NULL, delim);
}
return 0;
}
运行结果如下:
So
you've
never
programmed
before
As
we
go
through
this
tutorial
I
will
attempt
to
teach
you
how
to
program