Skip to content

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

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

#include <stdio.h>
#include <string.h>
#define MAXLINE 1000 /* maximum input line length */

int getsline(char line[], int max);
int strindex(char source[], char searchfor[]);

char pattern[] = "bc"; /* pattern to search for */

/* find all lines matching pattern */
int main()
{
    char line[MAXLINE];
    int found = 0;
    int pos = 0;

    while (getsline(line, MAXLINE) > 0)
    {
        pos = strindex(line, pattern);
        if (pos >= 0) 
        {
            printf("Rightmost occurene of %s in %s is = %d\n", pattern, line, pos);
            found++;
        }
        else 
            printf("Match pattern not found !\n");
    }

    return found;
}

/* getsline: get line into s, return length */
int getsline(char s[], int lim)
{
    int c, i;
    i = 0;

    while (--lim > 0 && (c=getchar()) != EOF && c != '\n')
        s[i++] = c;
    if (c == '\n')
        s[i++] = c;
    s[i] = '\0';

    return i;
}

/* strindex: return position of the rightmost occurrence of t in s, -1 if none */
int strindex(char s[], char t[])
{
    int i, j, k;

    for (i = strlen(s) - 1; i >= 0; i--) 
    {
        for (j=i, k=0; t[k]!='\0' && s[j]==t[k]; j++, k++)
            ;
        if (k > 0 && t[k] == '\0')
            return i;
    }

    return -1;
}
Back to top