The C Programming Language, 2nd Edition, by Kernighan and Ritchie
Exercise 4.01 on page 71

Write the function strrindex(s,t) , which returns the position of the rightmost occurrence of t in s , or -1 if there is none.

Solutions by Rick Dearman and Pilcrow

/* Test driver by Richard Heathfield
 * Solution (strrindex function) by Rick Dearman
 */

#include <stdio.h>

/* Write the function strrindex(s,t), which returns the position
** of the rightmost occurrence of t in s, or -1 if there is none.
*/

int strrindex( char s[], char t )
{
  int i;
  int count = -1;

  for(i=0; s[i] != '\0'; i++)
  {
    if(s[i] == t)
    {
      count = i;
    }
  }

  return count;
}


typedef struct TEST
{
  char *data;
  char testchar;
  int expected;
} TEST;

int main(void)
{
  TEST test[] =
  {
    {"Hello world", 'o', 7},
    {"This string is littered with iiiis", 'i', 32},
    {"No 'see' letters in here", 'c', -1}
  };

  size_t numtests = sizeof test / sizeof test[0];
  size_t i;

  char ch = 'o';
  int pos;

  for(i = 0; i < numtests; i++)
  {
    pos = strrindex(test[i].data, test[i].testchar);

    printf("Searching %s for last occurrence of %c.\n",
           test[i].data,
           test[i].testchar);

    printf("Expected result: %d\n", test[i].expected);
    printf("%sorrect (%d).\n", pos == test[i].expected ? "C" : "Inc", pos);
    if(pos != -1)
    {
      printf("Character found was %c\n", test[i].data[pos]);
    }
  }

  return 0;
}


Pilcrow's

/*****************************************************
Maybe my mind isn't complicated enough, but I thought
what was wanted was the rightmost position of one 
string in another. See K&R2 p69. -- Pilcrow
*****************************************************/

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

int strrindex(char[], char[]);

int main()
{
    char s[] = "cqabcdef";
    char t[] = "ef";
    char u[] = "cd";
    char v[] = "cqa";
    char z[] = "gh";
    int i;
    i = strrindex(s, t);
    if (i >=0)printf("'%s' matches '%s' at index %d\n",t,s,i);
    else printf("'%s' doesn't match '%s' at all\n",t,s);

    i = strrindex(s, u);
    if (i >=0)printf("'%s' matches '%s' at index %d\n",u,s,i);
    else printf("'%s' doesn't match '%s' at all\n",u,s);

    i = strrindex(s, v);
    if (i >=0)printf("'%s' matches '%s' at index %d\n",v,s,i);
    else printf("'%s' doesn't match '%s' at all\n",v,s);

    i = strrindex(s, z);
    if (i >=0)printf("'%s' matches '%s' at index %d\n",z,s,i);
    else printf("'%s' doesn't match '%s' at all\n",z,s);


    return 0;
}

int strrindex(char s[], char t[])
{
    int ls, lt, is, is2, it, match;
    ls = strlen( s);
    lt = strlen( t);
    match = -1;
    for(is = ls -1; is >= 0; is--) {
        for(it = 0, is2 = is; it < lt; it++, is2++) {
            if(t[it] != s[is2]){
                match = -1;
                break;
            }
            match = is;
        }
        if(it >= lt)return match;
    }
    return match;
}
Personal tools
Tidy_icons
not logged in