C语言中strspn()函数和strcspn()函数的对比使用
C语言strspn()函数:计算字符串str中连续有几个字符都属于字符串accept
头文件:#include<string.h>
strspn()函数用来计算字符串str中连续有几个字符都属于字符串accept,其原型为:
size_tstrspn(constchar*str,constchar*accept);
【函数说明】strspn()从参数str字符串的开头计算连续的字符,而这些字符都完全是accept所指字符串中的字符。简单的说,若strspn()返回的数值为n,则代表字符串str开头连续有n个字符都是属于字符串accept内的字符。
【返回值】返回字符串str开头连续包含字符串accept内的字符数目。所以,如果str所包含的字符都属于accept,那么返回str的长度;如果str的第一个字符不属于accept,那么返回0。
注意:检索的字符是区分大小写的。
提示:提示:函数strcspn()的含义与strspn()相反,可以对比学习。
范例:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
intmain()
{
inti;
charstr[]="129th";
characcept[]="1234567890";
i=strspn(str,accept);
printf("str前%d个字符都属于accept\n",i);
system("pause");
return0;
}
执行结果:
str前3个字符都属于accept
C语言strcspn()函数:计算字符串str中连续有几个字符都不属于字符串accept
头文件:#inclued<string.h>
strcspn()用来计算字符串str中连续有几个字符都不属于字符串accept,其原型为:
intstrcspn(char*str,char*accept);
【参数说明】str、accept为要进行查找的两个字符串。
strcspn()从字符串str的开头计算连续的字符,而这些字符都完全不在字符串accept中。简单地说,若strcspn()返回的数值为n,则代表字符串str开头连续有n个字符都不含字符串accept中的字符。
【返回值】返回字符串str开头连续不含字符串accept内的字符数目。
注意:如果str中的字符都没有在accept中出现,那么将返回atr的长度;检索的字符是区分大小写的。
提示:函数strspn()的含义与strcspn()相反,可以对比学习。
【示例】返回s1、s2包含的相同字符串的位置。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
intmain()
{
char*s1="http://c.biancheng.net/cpp/u/biaozhunku/";
char*s2="cisgood";
intn=strcspn(s1,s2);
printf("Thefirstcharbothins1ands2is:%c\n",s1[n]);
printf("Thepositionins1is:%d\n",n);
system("pause");
return0;
}
运行结果:
Thefirstcharbothins1ands2is:c Thepositionins1is:7
再看一个例子,判断两个字符串的字符是否有重复的。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
intmain()
{
char*s1="http://c.biancheng.net/cpp/xitong/";
char*s2="z-+*";
if(strlen(s1)==strcspn(s1,s2)){
printf("s1isdiffrentfroms2!\n");
}else{
printf("Thereisatleastonesamecharacterins1ands2!\n");
}
system("pause");
return0;
}
运行结果:
s1isdiffrentfroms2!
