C和指针之字符串strspn、strcspn函数源代码的实现

来源:互联网 发布:金融网络销售怎么做的 编辑:程序博客网 时间:2024/06/05 01:02

1、strspn strcspn介绍

1)size_t strspn(const char *str, const char * accept);

我的理解是字符串str中前面连续的字符有多少在accept中,如果哪一个没在accept中,就到这里结束了,后面不比了,比如
char *str = "xnufux dfafa";
char accept = "linux"
字符'x' 'n' 'u'都在"linux"里面,然后字符'f'不在"linux"里面,所以到这里不比了,结果就是3


2)size_t strcspn(const char *str, const char * accept);


它和strspn相反,可以这样理解,从字符串str头开始第几个字符在accept里面,就返回这个字符前面的字符个数,如果找不到就返回str的长度



3)、这里的测试代码有strspn和strcspn源码实现,然后还有用strcspn函数比较2个字符串的字符是否有重复的





2、测试代码

1、strcspn
#include <stdio.h>#include <string.h>int str_cspn(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)            {                return count;            }            if (*(a + 1) == '\0')                count++;        }    }    return count;}int main(){    char *str = "Linux was first developed for 386/486-based pcs. ";    printf("%d\n", str_cspn(str, " "));    printf("%d\n", strcspn(str, " "));    printf("%d\n", str_cspn(str, "/-"));    printf("%d\n", strcspn(str, "/-"));    printf("%d\n", str_cspn(str, "1234567890"));    printf("%d\n", strcspn(str, "1234567890"));    printf("%d\n", str_cspn(str, "A"));    printf("%d\n", strcspn(str, "A"));    //判断两个字符串的字符是否有重复的    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");    return 0;}

2、strspn
#include <stdio.h>#include <stdio.h>int str_spn(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)             {                 count++;                 break;             }        }        if (*a == '\0')           return count;    }    return count;}int main(){    const char *s = "chechechellochenyu";    const char *accept = "chne";    int result = str_spn(s, accept);    printf("result is %d\n", result);    printf("strspn(%s, %s) result is %d\n", s, accept, strspn(s, accept));    return 0;}





3、运行结果

1111deMacBook-Pro:dabian a1111$ gcc -g -w  strcspn.c -o strcspn1111deMacBook-Pro:dabian a1111$ ./strcspn55333330304949s1 is diffrent from s2!



1111deMacBook-Pro:dabian a1111$ vim strspn.c1111deMacBook-Pro:dabian a1111$ gcc -g -w  strspn.c -o strspn1111deMacBook-Pro:dabian a1111$ ./strspnresult is 9strspn(chechechellochenyu, chne) result is 9


原创粉丝点击