C Check Substring of a String C

Posted by user69514 on Stack Overflow See other posts from Stack Overflow or by user69514
Published on 2010-05-11T20:40:20Z Indexed on 2010/05/11 21:04 UTC
Read the original article Hit count: 267

I'm trying to check whether or not the second argument in my program is a substring of the first argument. The problem is that it only work if the substring starts with the same letter of the string.

EDIT: It must be done in C, not C++. Sorry

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

int my_strstr( char const *s, char const *sub ) {

    char const *ret = sub;

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


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

© Stack Overflow or respective owner

Related posts about string-manipulation

Related posts about chararray