string库之模拟实现strspn、strcspn与strpbrk

来源:互联网 发布:c语言布尔类型变量 编辑:程序博客网 时间:2024/05/18 02:50

原型:

    C库string.h中的strspn函数

描述:

    C 库函数 size_t strspn(const char *str1, const char *str2) 检索字符串 str1 中第一个不在字符串 str2 中出现的字符下标。

参数:

    str1:要被检索的 C 字符串。

    str2: 该字符串包含了要在 str1 中进行匹配的字符列表。

返回值:

    该函数返回 str1 中第一个不在字符串 str2 中出现的字符下标。

模拟实现strspn:

size_t my_strspn(const char *str1, const char *str2){int i = 0;char *pstr1 = (char *)str1;assert(NULL != str1);assert(NULL != str2);while (*pstr1){char *pstr2 = (char *)str2;while (*pstr2 && *pstr1 != *pstr2)++pstr2;if (*pstr1 == *pstr2)break;++pstr1;}return (pstr1 - str1);}

原型:

    C库string.h中的strcpsn函数

描述:

    C 库函数 size_t strcspn(const char *str1, const char *str2) 检索字符串 str1 开头连续有几个字符都不含字符串 str2 中的字符。

参数:

    str1:要被检索的 C 字符串。

    str2: 该字符串包含了要在 str1 中进行匹配的字符列表。

返回值:

    该函数返回 str1 开头连续都不含字符串 str2 中字符的字符数。

模拟实现strcspn:

    和strspn函数实现方式一样。



原型:

    C库string.h中的strcpsn函数

描述:

    C 库函数 char *strpbrk(const char *str1, const char *str2) 检索字符串 str1 中第一个匹配字符串 str2 中字符的字符,不包含空结束字符。也就是说,依次检验字符串 str1 中的字符,当被检验字符在字符串 str2 中也包含时,则停止检验,并返回该字符位置。

参数:

    str1:要被检索的 C 字符串。

    str2: 该字符串包含了要在 str1 中进行匹配的字符列表。

返回值:

    该函数返回 str1 中第一个匹配字符串 str2 中字符的字符数,如果未找到字符则返回 NULL。

模拟实现strpbrk:

char *my_strpbrk(const char *str1, const char *str2){char *pstr1= (char *)str1;assert(NULL != str1);assert(NULL != str2);while (*pstr1){char *pstr2 = (char *)str2;while (*pstr2 && (*pstr2 != *pstr1))++pstr2;if (*pstr2 == *pstr1)break;++pstr1;}return pstr1;}


    

注:这三种模拟实现的方式效率较低,可以利用数据结构中map相关知识优化算法。

0 0
原创粉丝点击