Check a substring of a string

I am trying to check if the second argument in my program is a substring of the first argument. The problem is that it only works if the substring starts with the same letter of the string.

EDIT: This should be done in C, not C ++.

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;
}

      

+2


a source to share


3 answers


Your analysis of the problem ("it only works if the substring starts with the same letter of the string") is incorrect and therefore you are looking for the wrong problem. Since this appears to be homework, I'm just hinting at the main problem.

As long as it doesn't work with Michigan

and igan

, it will work correctly with Michigan

and higan

.



Why does this work for higan

and not igan

? What is the first letter igan

? What is different from this when it comes to Michigan

?

+1


a source


I'm taking homework, so: See what gets initialized subStart

.



+2


a source


Your algorithm is wrong.

What you want is nested loops. Adjust the loop for length str

, then loop for length sub

to see if there is a match starting from that position.

+1


a source







All Articles