zoukankan      html  css  js  c++  java
  • strstr和memcmp函数的实现

    #include <stdio.h>
    #include <stdlib.h>			//malloc()函数
    typedef unsigned int size_t;
    
    size_t my_strlen(const char * str)
    {
    	const char *sc = NULL;
    	if(str == NULL)
    		return 0;
    	for(sc = str;*sc != '';sc++)
    	{
    		/*  do nothing */
    	}				
    	return sc - str;
    }
    
    /*  因为类型可以为任意,所以形参应为void *
     *  相等则返回0,否则不为0
     */
    int my_memcmp(const void *s1,const void *s2,size_t count)
    {
    	int res = 0;
    	const unsigned char *p1 =(const unsigned char *)s1;//注意是unsigned char *
    	const unsigned char *p2 =(const unsigned char *)s2;	
    	for(p1 ,p2;count > 0;p1++,p2++,count--)
    		if((res =*p1 - *p2) != 0)	//不相当则结束比较
    			break;
    	return res;
    }
    /* 查找字符串s2是否为s1的子串,s1为主串
     * 如果是则返回从第一个子串开始的字符串 
     */
    char * my_strstr(const char *s1,const char *s2)
    {
    	int len1,len2;
    	len2 = my_strlen(s2);	//获取子串s2的长度
    	if(!len2)				//如果子串s2为空则返回s1
    		return (char *)s1;	//先强制类型转换
    	len1 = my_strlen(s1);	//获取子串s1的长度
    	while(len1 >= len2)
    	{
    		len1--;
    		if(!my_memcmp(s1,s2,len2)) //my_memcmp返回0表示s1中存在s2的子串
    			return (char *)s1;	   //先强制类型转换
    		s1++;
    	}
    	return NULL;	//len1 < len2时返回空
    }
    
    int main()
    {
    	printf("%s
    ",my_strstr("hello world","world"));
    	printf("%s
    ",my_strstr("hello world","e"));
    	printf("%s
    ",my_strstr("hello world","llo"));
        return 0;
    }

    执行结果:



    2013年10月10日17:23分补充下面算法

    不使用库函数来实现strstr函数,效率其实也不高,高效率应该使用KMP法

    #include <stdio.h>
    
    char* strstr(char* buf, char* sub)
    {
    	char* bp;
    	char* sp;
    	if(sub == NULL)
    		return  buf;
    	while(buf !=NULL)
    	{
    		bp=buf;
    		sp=sub;
    		do{ 
    			if(!*sp)		//sp到最后即sub到最后则返回第一个子串在主串的位置
    				return buf;
    		}while(*bp++ == *sp++);
    		buf++;				//如果不等,主串buf+1,子串回溯到0
    	}
    	return 0;
    }
    
    int main()
    {
    	printf("%s
    ",strstr("hello world", "ell"));
        return 0;
    }

    执行结果:



  • 相关阅读:
    【转】Mybatis常见面试题总结
    【转】深入分析@Transactional的用法
    刷抖音极速版,大家一起来赚钱
    公司喜欢什么样的员工呢?
    边学习新技术边工作的重要性
    聊聊IT行业加班的问题
    软件工程师怎样减轻工作过程中遇到的压力
    如何找兼职工作
    常用的网址导航
    几家主要的配送(跑腿)服务提供商
  • 原文地址:https://www.cnblogs.com/suncoolcat/p/3362333.html
Copyright © 2011-2022 走看看