C程序语言strstr函数分析和使用

来源:互联网 发布:手机淘宝怎样修改星评 编辑:程序博客网 时间:2024/05/01 20:59

GCC 4.X中的strstr函数原型

1.函数原型

strstr (const char *s1, const char *s2) {   const char *p = s1;     const size_t len = strlen (s2);     //计算s2字符串的长度   for (; (p = strchr (p, *s2)) != 0; p++) //查找p字符串中*s2字符第一次出现的位置,返回一个指针,这个指针就是p字符串中*s2字符的位置   {     if (strncmp (p, s2, len) == 0)   //对比前p字符串和s2字符串中的前len个字符是否相同,如果是则返回0      return (char *)p;    //最后返回一个字符串s2在s1中的起始位置 返回是一个char类型的指针    }      return (0); }


2.自己编写此函数(不用任何函数库中的函数)

char *strfind(char *sc, char *dc){        char *fs = sc, *fd = dc;        char *dffs, *dffd;        int i, j = 0;        for (i = 0; *fd; fd++)   //代替strlen函数                i++;        fd -= i; j = i;        for (; *fs; fs++) {                if (*fs == *fd) {           //代替strchr函数                        dffs = fs; dffd = fd;                        while (*++dffs == *++dffd && *dffs && --j) ;           //代替strncmp函数                        if (j == 1)                                return (char *)fs;                        else                                j = i;                }        }        return (0);}


3.测试

[root@cache aaa]# cat strfind.c #include <stdio.h>#include <string.h>char *strfin(char *sc, char *dc){char *fs = sc, *fd = dc;char *dffs, *dffd;int i, j = 0;for (i = 0; *fd; fd++)i++;fd -= i; j = i;for (; *fs; fs++) {if (*fs == *fd) {dffs = fs; dffd = fd;while (*++dffs == *++dffd && *dffs && --j) ;if (j == 1)return fs;else j = i;}}return (0);}main(){char *sc = "authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost=121.11.79.137  user=root";char *fc = " user=";fprintf(stdout, "strfin's = %s\n", strfin(sc , fc));fprintf(stdout, "strstr's = %s\n", strstr(sc , fc));return (0);}[root@cache aaa]# !cccc strfind.c  [root@cache aaa]# ./a.out //输出结果一样strfin's =  user=rootstrstr's =  user=root


################

迷途小运维随笔

作者:john

转载请注明出处

原创粉丝点击