2020oop first exercise 6-3 String- 6. Find substring (BF algorithm) (10 points)

The C language standard function library includes the strstr function, which searches for substrings in the main string. As an exercise, let's write a function ourselves that does the same.

function prototype

char* StrStr(const char *txt, const char *pat);

Description: txtand are the starting addresses of the main string and substring patrespectively . If the search is successful, the function value is the starting address of the first occurrence of the substring in the main string, otherwise the function value is NULL.

In particular, we make appropriate modifications to the C language library function strstr: if the substring is an empty string, it has no meaning, and the function value is specified as NULL.

referee procedure

#include <stdio.h>
#include <string.h>

char* StrStr(const char *txt, const char *pat);

int main()
{
    char m[1024], s[1024], *p;
    gets(m);
    gets(s);
    p = StrStr(m, s);
    if (p)
    {
        printf("%d\n", p - m);
    }
    else
    {
        puts("NULL");
    }
    return 0;
}

/* 你提交的代码将被嵌在这里 */

Input sample 1

This is a pencil
is

output sample 1

2

Input sample 2

This is a pencil
be

Output sample 2

NULL

Initial code (AC)

char* StrStr(const char *txt, const char *pat){
    int i=0,j=0,m=0,n=0;
    char *q=(char *)txt,*o=(char *)pat,*flag;
    while(txt[m]!='\0') m++;
    while(pat[n]!='\0') n++;
    if(n==0) return NULL;
    while(i<m&&j<n)
    {
        if(q[i]==o[j]) {i++;j++;}
        else{
            j=0;i=i-j+1;
        }
    }
    if(j>=n) return q+(i-n);
    return NULL;
}

 later

char* StrStr(const char *txt, const char *pat){     if(txt==NULL) return NULL;     else{         int i,j;//Because after the loop ends, ij is still needed for judgment, so declare         int in advance la=strlen(txt), lb=strlen(pat);         for(i=0;i<la-lb;i++){//i is less than la+lb             for(j=0;j<lb;j++)                 if(txt[i+j]!=pat[j])                     break;             }             if(j==lb){//judging whether the same string is found                 return (char *)txt+i;//             }//txt It is a pointer of const char * type, which needs to be converted by (char *)         }//Use txt+i directly, the program will report an error     }     return NULL; }















Summarize

A pointer of const char * type, which needs to be converted when used

Guess you like

Origin blog.csdn.net/qq_45788060/article/details/108120361