版权声明:转载请声明原文链接地址,谢谢! https://blog.csdn.net/weixin_42859280/article/details/85924397
源代码:
#include <stdio.h>
#include<string.h>
int main()
{
char str[] = "经度:111°11’11'' 纬度: 30°30'30''";
char *p;
char a[]=" ";
p = strtok(str, ":");
int i=0;int n;
while(p)
{
printf("第%d个:%s\n", i+1,p);
//这里计算次数进行赋值输出
p = strtok(NULL, " ");
i++;
}
printf("%d",i);
return 0;
}
char *strtok(char *s, char *delim);
功能:分解字符串为一组标记串。s为要分解的字符串,delim为分隔符字符串。
说明:首次调用时,s必须指向要分解的字符串,随后调用要把s设成NULL。
strtok在s中查找包含在delim中的字符并用NULL(’\0’)来替换,直到找遍整个字符串。
返回指向下一个标记串。当没有标记串时则返回空字符NULL。
函数strtok()实际上修改了有str1指向的字符串。
每次找到一个分隔符后,一个空(NULL)就被放到分隔符处,函数用这种方法来连续查找该字符串。
示例:
#include <string.h>
#include <stdio.h>
int main()
{
char *p;
char str[100]="This is a test ,and you can use it";
p = strtok(str," "); // 注意,此时得到的 p为指向字符串:"This",即在第一个分隔 符前面的字符串,即每次找到一个分隔符后,一个空(NULL)就被放到分隔符处,所以此时NULL指针指向后面的字符串:"is a test ,and you can use it"。
printf("%s\n",p); // 此时显示:This
do
{
p = strtok(NULL, ","); // NULL 即为上面返回的指针,即字符串:
// "is a test ,and you can use it"。
if(p)
printf("|%s",p);
}while(p);
system("pause");
return 0;
}