C函数库中的strspn实现

/*
*copyright@nciaebupt 转载请注明出处
*原型:size_t strspn(const char * str1,const char * str2);
*用法:#include <string.h>
*功能:若strspn()返回的数值为n,
*       则代表字符串str1开头连续有n个字符都是属于字符串str2内的字符.
*说明:返回字符串str1开头连续包含字符串str2内的字符数目.
*使用C函数库中的strspn
*/
#include <cstdio>
#include <cstring>

int main(int args,char ** argv)
{
    char str[] = "12999th";
    char keys[] = "1234567890";

    int i = strspn(str,keys);

    printf("the initial string has %d numbers\n",i);

    getchar();
    return 0;
}

/*
*copyright@nciaebupt 转载请注明出处
*原型:size_t strspn(const char * str1,const char * str2);
*用法:#include <string.h>
*功能:若strspn()返回的数值为n,
*       则代表字符串str1开头连续有n个字符都是属于字符串str2内的字符.
*说明:返回字符串str1开头连续包含字符串str2内的字符数目.
*自己实现strspn
*/
#include <cstdio>
#include <cstring>

size_t _strspn(const char * string,const char * control)
{
    const char * str = (const char *)string;
    const char * ctrl = (const char *)control;
    unsigned char map[32];
    int count = 0;
    /*clear the map*/
    memset(map,0,32*sizeof(unsigned char));
    //memset(map,0,32);
    /*set bits in control map*/
    while(*ctrl)
    {
        map[*ctrl >> 3] |= (0x01 << (*ctrl & 7));
        ctrl++;
    }
    /*count the str's char num in control*/
    if(*str)
    {
        count = 0;

        while((map[*str >> 3] & (0x01 << (*str & 7))))
        {
            count++;
            str++;
        }
        return count;
    }
    return 0;
}

int main(int args,char ** argv)
{
    char str[] = "129th";
    char keys[] = "1234567890";

    int i = _strspn(str,keys);

    printf("the initial string has %d numbers\n",i);

    getchar();
    return 0;
}

你可能感兴趣的:(C函数库中的strspn实现)