-2

So, I have written a mystrstr() function which should behave exactly as the original strstr() function. I have tested huge amount of cases and my function seems to work. However, it does not pass some of the tests of the online submission system.

Can you help me?

int mystrcmp(char *a, char *b)
{
    int n = mystrlen(a);
    int m = mystrlen(b);
    int l = n;
    if (m<n) l = m;

    //printf("strcmp => %d %d\n", n, m);
    for (int i=0; i<l; i++)
    {
        //printf("%c %c\n",a[i],b[i]);
        if (a[i]<b[i]) return -2;
        else if (a[i]>b[i]) return 2;
    }

    if (n<m) return -1;
    else if (n>m) return 1;
    else return 0;
}


char *mystrstr(char *haystack, char *needle)
{
    int n = mystrlen(haystack);
    int m = mystrlen(needle);
    if (n==0&&m==0) return haystack;
    int result;

    for (int i=0; i<=(n-m); i++)
    {
        result = mystrcmp(haystack+i, needle);
        if (result==1||result==0||result==-1)
            return haystack+i;
    }
    return NULL;
}
DrM
  • 1,092
  • 1
  • 8
  • 11
Azad Salahli
  • 876
  • 3
  • 14
  • 30

2 Answers2

0

Note that your mystrcmp is redundant. You can just use

if (!memcmp(haystack+i, needle, m)) {
     return haystack+i
}

If you are not allowed to use memcmp then write your own. But discard mystrcmp.

William Morris
  • 3,554
  • 2
  • 23
  • 24
  • I believe that is what you are talking about: `mystrstr("abcd","");` . It actually returns "abcd", which is the expected result. – Azad Salahli Nov 18 '12 at 04:20
  • About `mystrcmp`. I was required to write it as part of my homework. As long as it works, I don't have problem with it. But, I am curious, what is the difference between using `memcmp` and `strcmp`? – Azad Salahli Nov 18 '12 at 04:23
  • `memcmp` has a simpler job than `strcmp` as it must only check a known number of bytes for equivalence; `strcmp` must worry about not going beyond the end of each string. Yes, your function does work with needle=="". Sorry! – William Morris Nov 18 '12 at 13:43
-4
if (n==0&&m==0) return haystack; 

You want "||" operator.

if (m<n) l = m;

You know if "m != n" then the two string do not have equal length, hence are not equal.

Not sure about the rest, didn't look to much further.

dchhetri
  • 6,926
  • 4
  • 43
  • 56
  • 2
    “You know if "m != n" then the two string do not have equal length, hence are not equal” Yes, but the goal of function `strcmp` is not just to tell if the strings are equal. It is to order them. In the particular case of this implementation, a third function is obviously to tell if one is a prefix of the other. – Pascal Cuoq Nov 18 '12 at 00:23
  • 2
    “You want "||" operator.” No, if m==2, n==0, the function should not return `haystack`. – Pascal Cuoq Nov 18 '12 at 00:25
  • `if (n==0&&m==0) return haystack;` That's not correct, since if n=0 and m!=0, I want to return NULL – Azad Salahli Nov 18 '12 at 00:25