C - check if a string is a substring of another string

I need to write a program that takes two lines as arguments and checks if the second is a substring of the first. I need to do this without using any special library functions. I created this implementation, but I think that it always returns true if there is one letter that is the same on both lines. You can help me here. I'm not sure what I'm doing wrong:

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

int my_strstr( char const *s, char const *sub ) {
    char const *ret = sub;

    int r = 0;
    while ( ret = strchr( ret, *sub ) ) {
        if ( strcmp( ++ret, sub+1 ) == 0 ){
            r = 1;
        }
        else{
            r = 0;
        }        
    }
    return r;
}

int main(int argc, char **argv){

    if (argc != 3) {
        printf ("Usage: check <string one> <string two>\n");
    }
    int result = my_strstr(argv[1], argv[2]);

    if(result == 1){
        printf("%s is a substring of %s\n", argv[2], argv[1]);
    } else{
        printf("%s is not a substring of %s\n", argv[2], argv[1]);
    }
    return 0;
}
+3
source share
6 answers

Your approach to writing strstris fundamentally wrong. Let's see what you wrote:

char const *ret = sub;

int r = 0;
while ( ret = strchr( ret, *sub ) ) {
    if ( strcmp( ++ret, sub+1 ) == 0 ){
        r = 1;
    }
    else{
        r = 0;
    }        
}
return r;

, ret, sub, sub s. , ret s...

ret = strchr( ret, *sub ) sub ret, ret, .

strcmp( ++ret, sub+1 ), , , ret, , sub, ret, ( , ).

, , . , s, s .

, :

  • sub s. , false.
  • s,
  • , sub n, , n s sub ( s). , true. s .

, - sub, . , sub sub s, , sub. , s , , .

+3

, ret my_strstr. strcmp , . , strncmp.

+1

, char * sub char * sub:

int my_strstr( char const *s, char const *sub ) {
char const *ret = sub;

ret s?

strcmp , , strcmp ( "abcde", "abc" ) false. , strncmp, , .

0

ret = strchr( ret, *sub )

ret == sub. , strchr(ret, *sub) char ret ret. ret.

, ret .

,

strcmp( ++ret, sub+1 ) == 0 

ret - sub, true.

1 .

0

-. : 1) 2) , . .

, , . , , .. , , false. , true. strncmp, (strncmp(a, b, strlen(b)) == 0) (, b ).

-, , , . , , . , my_function("This is a sample string", 's'), , 's' , . , , - , .

, "", "", "", .

0
char const *ret = sub;

int r = 0;
while ( ret = strchr( ret, *sub ) ) {

ret stores the address of the auxiliary array and in the while expression strchr(ret,*sub) comparing the value in subwith the address stored in ret whether it will work or not (is this comparison correct or not) please reply ...

0
source

Source: https://habr.com/ru/post/1740811/


All Articles