zoukankan      html  css  js  c++  java
  • 仰视源码,实现strstr和find

    字符串查找两种情况,查找返回子字符串的指针位置和在字符串中的位置。strstr和find的实现是基于源码来实现的,然而字符串匹配方法依然可以用在字符串查找上,字符串匹配方法很多,但是源码却采用这种最为直观的方式来实现,是它的一个权衡。比起我们的暴力查找,它还是很高效的,所以,学习学习。

    1.查找字符串src中的子串,若成功返回子串在src中的起始指针。

    const char* strstr(const char* src, const char* sub)
    {
    	if (src == NULL && sub == NULL)
    	{
    		return src;
    	}
    	const char* ps = src;
    	const char* pb = sub;
    	while (*src)
    	{
    		do 
    		{
    			if (!*ps)
    			{
    				return src;
    			}
    		} while (*pb++ == *ps++);
    		src++;
    	}
    	return NULL;
    }

    2.查找src中的子字符串,返回字符串在src中的起始位置。

    int myfind(const char* src, const char* sub)
    {	
    	if (src == NULL && sub == NULL)
    	{
    		return -1;
    	}
    	const char* ps;
    	const char* pb;
    	int rtn = 0;
    	while (*src)
    	{
    		ps = src;
    		pb = sub;
    		do 
    		{
    			if (!*pb)
    			{
    				return rtn;
    			}
    		} while (*pb++ == *ps++);
    		src++;
    		rtn++;
    	}
    	return NULL;
    }
    


    虽然这是C/C++的实现,但是依然可以用在C#,java中。

    生命不止,奋斗不息!
  • 相关阅读:
    Linux下批处理文件
    linux代码端启动终端
    ubuntu截图
    Ubuntu安装多个版本的Opencv
    Ubuntu双系统启动卡死
    Ubuntu14.04运行lsdslam与问题解决
    js懒加载
    公众号开发-获取用户信息
    ClipboardJS 复制文本功能
    css3 Gradient线性渐变详解
  • 原文地址:https://www.cnblogs.com/huzongzhe/p/6735171.html
Copyright © 2011-2022 走看看