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

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]# !cc
cc strfind.c  
[root@cache aaa]# ./a.out //输出结果一样
strfin's =  user=root
strstr's =  user=root


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

迷途小运维随笔

作者:john

转载请注明出处

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值