魔兽贱队 发表于 2017-6-1 13:34:24

算法练习Mystrstr

草稿
hello wolrd

hxl

if(*pFirst == *pFindFirst)
    pFirst ++;
    pFindFirst ++;

    if(*pFirst == *pFindFirst)
      pFirst ++;
      pFindFirst ++;

for(int i ; i < strlen(hello wolrd) ; i++)
{

    if(*pFindFirst == '\0')
      return 0;

    if(*pFirst == *pFindFirst)
    {
      pFirst++;
      pFindFirst++;
      count ++;
      if(count == strlen(hel))
            return pFirst - count;
      continue;
    }else
    {
      count = 0;
      pFindFirst = findstr;
      pFirst++;
    }

}

return 0;


于是有了下面代码


#include <stdio.h>
#include <Windows.h>

size_t mystrlen(const char* str)
{
    return (NULL == str || *str =='\0') ? 0 : mystrlen(str+1) + 1;
}


char* mystrstr(const char* Srcstr, const char* findstr)
{
    if(Srcstr == NULL || findstr == NULL || *Srcstr == '\0' ||*findstr == '\0')
      return NULL;

    const char *pFindFirst = findstr;
    const char* pFirst = Srcstr;
    int count = 0;
    int findstrlen = mystrlen(findstr);
    int srclen = mystrlen(Srcstr);

    for(int i = 0 ; i < srclen ; i++)
    {
      if(*pFindFirst == '\0')
            return NULL;

      if(*pFirst == *pFindFirst)
      {
            pFirst++;
            pFindFirst++;
            count ++;
            if(count == findstrlen)
                return (char*)(pFirst - count);
            continue;
      }else
      {
            count = 0;
            pFindFirst = findstr;
            pFirst++;
      }

    }

    return NULL;
}



void main()
{
    EX:
    char *str = (char*)malloc(250);
    char *findstr = (char*)malloc(250);

    memset(str,'\0',250);
    memset(findstr,'\0',250);

    printf("input src string :");
    gets(str);
    printf("\ninput find string :");
    gets(findstr);
    printf("\n");

    char* pRetstr = mystrstr(str, findstr);

    if(pRetstr != NULL)
      printf("find string is :%s\n",pRetstr);
    else
      printf("no find!\n");

    printf("ExitProcess ? Y # N\n");
    memset(str,'\0',250);
    gets(str);
    if(*str == 'n' || *str == 'N')
      goto EX;
    else
    {
      free(str);
      free(findstr);
      ExitProcess(0);
    }
}
页: [1]
查看完整版本: 算法练习Mystrstr