开发者

Check substring of a string

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++.

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

    if (argc != 3) {
        p开发者_如何学Pythonrintf ("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;
}


I am assuming homework, so: Take a look at what subStart is initialized with.


Your analysis of the problem ("it only work if the substring starts with the same letter of the string") is incorrect and so you are looking for the wrong problem. Since this appears to be homework, I'll just hint at the underlying problem.

While it fails with Michigan and igan it will correctly work with Michigan and higan.

Why does it work for higan and not igan? What is the first letter of igan? What is different about that when it comes to Michigan?


Your algorithm isn't correct.

What you want is nested loops. Loop over the length of str, then loop over the length of sub to see if there is a match starting at that position.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜