2

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) {
        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;
}
5
  • … specifically, homework which forbids you to use any library functions besides at? Commented May 11, 2010 at 20:48
  • 2
    When you pass strings to functions, use 'const string&'. Commented May 11, 2010 at 20:50
  • 2
    Why is the standard C strstr function not acceptable? Commented May 11, 2010 at 21:13
  • 3
    Please don't edit questions in a way that answers already given are invalidated. Commented May 11, 2010 at 23:21
  • 1
    Where's the definition of my_strstr? Commented May 11, 2010 at 23:39

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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?

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.