strcspn和strspn函数

1、strcspn

头文件:#inclued<string.h>

定义函数:size_t strcspn(const char *s, const char * reject);

函数说明:strcspn()从参数s 字符串的开头计算连续的字符, 而这些字符都完全不在参数reject所指的字符串中. 简单地说, 若strcspn()返回的数值为n, 则代表字符串s 开头连续有n 个字符都不含字符串reject内的字符.

返回值:返回字符串s 开头连续不含字符串reject 内的字符数目.

范例
#include <string.h>
main()
{
    char *str = "Linux was firstdeveloped for 386/486-based pcs. ";
    printf("%d\n", strcspn(str, ""));
    printf("%d\n", strcspn(str,"/-"));
    printf("%d\n", strcspn(str,"1234567890"));
}

执行结果:
5 //只计算到" "的出现, 所以返回"Linux"的长度
33 //计算到出现"/"或"-", 所以返回到"6"的长度
30 // 计算到出现数字字符为止, 所以返回"3"出现前的长度
 
 
2、strspn
strspn(返回字符串中第一个不在指定字符串中出现的字符下标)
表头文件 #include<string.h>
定义函数 size_t strspn (const char *s,const char * accept);
函数说明 strspn()从参数s 字符串的开头计算连续的字符,而这些字符都完全是accept 所指字符串中的字符。简单的说,若strspn()返回的数值为n,则代表字符串s 开头连续有n 个字符都是属于字符串accept内的字符。
返回值 返回字符串s开头连续包含字符串accept内的字符数目。

1 #include <string.h>
2 #include <stdio.h>
3 main()
4 {
5 char *str="Linux was first developed for 386/486-based pcs.";
6 printf("%d\n",strspn(str,"Linux"));
7 printf("%d\n",strspn(str,"/-"));
8 printf("%d\n",strspn(str,"1234567890"));
9 }
运行结果:
5  //包含linux字符切 
// 开始不包含  
  //开始不包含
函数原型:
int strspn(const char *s,const char *accept)
{
const char *p;
const char *a;
int count = 0;
for(p = s; *p != '\0'; ++p)
{
for (a = accept; *a != '\0'; ++a)
{
if (*p == *a)
{
break;
}
}//里面的for循环到此为止
if (*a == '\0')
{
return count;
}
++count;
}//外面的for循环到此为止
return count;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值