zoukankan      html  css  js  c++  java
  • 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);
    }
    
  • 相关阅读:
    004---基于TCP的套接字
    003---socket介绍
    002---tcp/ip五层详解
    001---C/S架构
    008---re正则模块
    007---logging日志模块
    006---hashlib模块
    005---json & pickle
    004---os & sys
    22.解决 eclipse 与 AS 共用 SDK 导致 eclipse ADT 无法使用的问题
  • 原文地址:https://www.cnblogs.com/helloweworld/p/2804760.html
Copyright © 2011-2022 走看看