views:

120

answers:

6

Corrected code:

int strrindex(char *s, char *t) {
  int i, j, k, p;

  i = -1;
  for (k = 0; s[k] != '\0'; k++) {
    if (strlen(s) < strlen(t)) break;
    if (s[k] == t[0]) {
      for (p = k; s[p] != '\0'; p++) {
    j = p;
        while (s[j] != '\0' && s[j] == t[j-k] && t[j-k] != '\0') { j++; } 
        if (t[j-k] != '\0') { break; }
    i = k;
      }
    }
  }

  printf("%d\n", i);
  return 0;
}
A: 

I think this should work:

 int strrindex(char *s, char *t) {

  int i = -1;
  int j = 0;
  int k = 0;
  for (; s[k]; k++) {
    if(!t[j]) {
      i = k - j;
      j = 0;
    }
    if (s[k] != t[j])
      j = 0;
    else
      j++;
  }
  if(!t[j + 1])
    i = k - j - 1;

  return i;
}
inflagranti
Didn't really want the answer :) but thanks
lame
It may not be the final answer, as I didn't test it (may have off by one errors...). But it's an alternative approach using only one loop :)
inflagranti
Hehe. We all started like that :) Next time you do something similar, it may only take you a few hours ;) Also, as other people suggested, try using more descriptive variable names (I'm no good role model there...) And I really doubt it will work for any border case (i.e. did you try with the strings being the same?).
inflagranti
A: 
  • Your loop over p is indexing both s[p] and t[p]. That's incorrect, since they're both different indices.
  • Your if (s[p] != t[p] ...) i = -1; has no effect, because you then immediately set it to k.
Stephen
Will modify accordingly and report back. Thanks
lame
+1  A: 
  for (p = k; s[p] != '\0'; p++) {
    while (s[p] == t[p] && t[p] != '\0') { p++; }

At this point, you are comparing string s starting at position p with string t starting at position 0. So it shouldn't be t[p], but instead t[p - k].

    if (s[p] != t[p] || t[p] != '\0') { i = -1; }

You don't need this at all - if the current section doesn't match, you just leave i at the last match. (which will anyway be -1 if there has been no match so far)

casablanca
You don't need that long `if` statement. Try this instead: `if (t[p-k] == '\0') i = k;` - this basically accepts the current substring if all characters matched.
casablanca
A: 

You're not the first person to want such a function.

See: Is there a reverse fn() for strstr? for some example implementations.

fmark
A: 
Owen S.
Um. Well, you fixed one of them. :-P
Owen S.
1) Just noted that the inner for loop is unnecessary (modified answer), 2) putting j = p into the test is IMO bad style.
Owen S.
A: 

There's a great reference on substring search algorithms here: http://www-igm.univ-mlv.fr/~lecroq/string/index.html

With any of them, you can simply switch things around to start with pointers to the last byte of the string and negate the indices.

R..