strspn函数 strcspn函数

来源:互联网 发布:js获得div style 编辑:程序博客网 时间:2024/05/03 02:27

引子:

我们知道wal日志文件名字为24位0-F字符组成tli+logid+segid("%08X%08X%08X", tli, log, seg),那么给出一个文件名,如何判断其是否符合上述规则?

思路:

1.判断是否是24位

2.for循环,用每一位来做判断看是否属于0-F


linux函数已实现上述功能,函数为int strspn(const char* source, const char*accept)

该函数作用:

给出字符串source, 以及指定规则字符串 accept,返回字符串source中起始部分连续在accept字符串中的字符的个数(有n个字符在则返回n)。

头文件 <string.h>


源码中使用的为:strspn(nextWALFileName, "0123456789ABCDEF") == 24

示例:

iZ232ngsvp8Z:~/tmp # cat strspn1.c #include <string.h>#include <stdio.h>int main(){    char *str="2015 abcd";    fprintf(stdout,"%d\n",strspn(str,"0123456789"));    fflush(stdout);}iZ232ngsvp8Z:~/tmp # ./strspn1 4


查看帮助信息

iZ232ngsvp8Z:~/tmp # man strspnSTRSPN(3)                                            Linux Programmer's Manual                                           STRSPN(3)NAME       strspn, strcspn - search a string for a set of charactersSYNOPSIS       #include <string.h>       size_t strspn(const char *s, const char *accept);       size_t strcspn(const char *s, const char *reject);DESCRIPTION       The strspn() function calculates the length of the initial segment of s which consists entirely of characters in accept.       The  strcspn()  function  calculates  the  length  of the initial segment of s which consists entirely of characters not in       reject.RETURN VALUE       The strspn() function returns the number of characters in the initial segment of s which consist only  of  characters  from       accept.       The strcspn() function returns the number of characters in the initial segment of s which are not in the string reject.CONFORMING TO       SVr4, 4.3BSD, C89, C99.SEE ALSO       index(3), memchr(3), rindex(3), strchr(3), strpbrk(3), strsep(3), strstr(3), strtok(3), wcscspn(3), wcsspn(3)COLOPHON       This  page  is  part  of  release 3.15 of the Linux man-pages project.  A description of the project, and information about       reporting bugs, can be found at http://www.kernel.org/doc/man-pages/.


由于功能类似,这里再介绍linux函数 strcspn, 具体见上面帮助信息。

该函数作用:

同strspn作用相反,strcspn 则为在字符串sourc中起始部分连续不在reject字符串的长度。

该函数可以用来查看某个字符在指定字符串中第一次出现的位置。


示例如下:

iZ232ngsvp8Z:~/tmp # cat strspn1.c #include <string.h>#include <stdio.h>int main(){    char *str="2a015 abcd";    fprintf(stdout,"%d\n",strcspn(str,"0123456789"));    fflush(stdout);}iZ232ngsvp8Z:~/tmp # ./strspn1 0iZ232ngsvp8Z:~/tmp # cat strspn1.c #include <string.h>#include <stdio.h>int main(){    char *str="abcd2015 abcd";    fprintf(stdout,"%d\n",strcspn(str,"0123456789"));    fflush(stdout);}iZ232ngsvp8Z:~/tmp # ./strspn1 4




0 0