• strstr 的实现 即 字符串中查找子字符串第一次出现的位置


    /***
    *char *strstr(string1, string2) - search for string2 in string1
    *
    *Purpose:
    *       finds the first occurrence of string2 in string1
    *
    *Entry:
    *       char *string1 - string to search in
    *       char *string2 - string to search for
    *
    *Exit:
    *       returns a pointer to the first occurrence of string2 in
    *       string1, or NULL if string2 does not occur in string1
    *
    *Uses:
    *
    *Exceptions:
    *
    *******************************************************************************/
    
    char * __cdecl strstr (
            const char * str1,
            const char * str2
            )
    {
            char *cp = (char *) str1;
            char *s1, *s2;
    
            if ( !*str2 )
                return((char *)str1);
    
            while (*cp)
            {
                    s1 = cp;
                    s2 = (char *) str2;
    
                    while ( *s1 && *s2 && !(*s1-*s2) )
                            s1++, s2++;
    
                    if (!*s2)
                            return(cp);
    
                    cp++;
            }
    
            return(NULL);
    
    }
    
    /*同时,自己写的,朴素的查找子串算法*/
    #include <iostream>
    #include <stdio.h>
    using namespace std;
    
    char *mystrstr(char *string, char *substring)
    {
    	char *pstr = string;
    	char *tmpstr, *psub;
    
    	//外循环是主串不到末尾则一直do
    	while (*pstr) {
    		tmpstr = pstr;
    		psub = substring;
    
    		//从主串的某个位置开始,判断其后的字符串是否为子串。
    		while (*tmpstr && *psub && !(*tmpstr - *psub)) {
    			tmpstr++;
    			psub++;
    		}
    
    		if (!(*psub)) {
    			return pstr;
    		}
    
    		//主串对比位置后移一个字符。
    		pstr++;
    	}
    
    	return NULL;
    }
    
    int main()
    {
    	char s1[20] = "helloworld";
    	char s2[10] = "wo";
    	cout << mystrstr(s1, s2);
    }
    
  • 相关阅读:
    【cocos2d-js网络教程篇】cocos2d-js http网络请求
    COCOS2D
    Laravel5中的Session
    Laravel 下配置 Redis 让缓存、Session 各自使用不同的 Redis 数据库
    cocos-js Http方式网络请求
    Python语法31[module/package+import]
    cocos2d-js callFunc传参
    安装pygame for Python3.5
    阿里云vsftp安装和简单的配置
    Git代码行统计命令集
  • 原文地址:https://www.cnblogs.com/helloweworld/p/2804760.html
Copyright © 2020-2023  润新知