linux str函数,Linux下C语言字符串处理函数之strspn()、strcspn()、strbrk()的介绍使用...

部分参考网络资源,地址不可考,谢谢原作者!

一、strspn()函数:计算字符串str中连续有几个字符都属于字符串accept

头文件:#include 函数原型 size_t strspn(const char *str, const char * accept);

函数说明

strspn() 从参数 str 字符串的开头计算连续的字符,而这些字符都完全是 accept 所指字符串中的字符。简单的说,若 strspn() 返回的数值为n,则代表字符串 str 开头连续有 n 个字符都是属于字符串 accept 内的字符。

返回值

返回字符串 str 开头连续包含字符串 accept 内的字符数目。所以,如果 str 所包含的字符都属于 accept,那么返回 str 的长度;如果 str 的第一个字符不属于 accept,那么返回 0。

注意:检索的字符是区分大小写的。

提示:函数 strcspn() 的含义与 strspn() 相反,可以对比学习。

范例:

1

2

3

4

5

6

7

8

9

10

11

12

13

#include

#include

#include

int main ()

{

int i;

char str[] ="129th";

char accept[] ="1234567890";

i =strspn(str, accept);

printf("str 前 %d 个字符都属于 accept\n",i);

system("pause");

return 0;

}

执行结果:

1

str 前 3 个字符都属于 accept

二、strcspn()函数:计算字符串str中连续有几个字符都不属于字符串accept

头文件:#inclued

函数原型

1

int strcspn(char *str,char *accept);

参数说明

str、accept为要进行查找的两个字符串。

strcspn() 从字符串 str 的开头计算连续的字符,而这些字符都完全不在字符串 accept 中。简单地说,若 strcspn() 返回的数值为 n,则代表字符串 str 开头连续有 n 个字符都不含字符串 accept 中的字符。

返回值返回字符串 str 开头连续不含字符串 accept 内的字符数目。

注意如果 str 中的字符都没有在 accept 中出现,那么将返回 atr 的长度;检索的字符是区分大小写的。

提示函数 strspn() 的含义与 strcspn() 相反,可以对比学习。

示例——返回s1、s2包含的相同字符串的位置。

1

2

3

4

5

6

7

8

9

10

11

12

13

#include

#include

#include

int main()

{

char* s1 ="http://c.biancheng.net/cpp/u/biaozhunku/";

char* s2 ="c is good";

int n =strcspn(s1,s2);

printf("The first char both in s1 and s2 is :%c\n",s1[n]);

printf("The position in s1 is: %d\n",n);

system("pause");

return 0;

}

运行结果:

1

2

The first char both in s1 and s2 is :c

The position in s1 is: 7

再看一个例子,判断两个字符串的字符是否有重复的。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

#include

#include

#include

int main()

{

char* s1 ="http://c.biancheng.net/cpp/xitong/";

char* s2 ="z -+*";

if(strlen(s1) ==strcspn(s1,s2)){

printf("s1 is diffrent from s2!\n");

}else{

printf("There is at least one same character in s1 and s2!\n");

}

system("pause");

return 0;

}

运行结果:

1

s1 is diffrent from s2!

三、函数strpbrk

头文件:

函数描述:查找字符串strCharSet中任一字符在字符串string中第一次出现的位置;

函数原型:char *strpbrk( const char*string, const char*strCharSet );

参数说明:string待搜索的字符串; strCharSet设置搜索字符

返回值:函数返回一个指针,指向字符串strCharSet中任一字符在字符串string中第一次出现的位置,若string中不包含strCharSet中的字符,则返回空指针NULL。

实例:

待续。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值