Create a function which returns the position of the rightmost occurrence of t in s, or -1 if there is none. - C String

C examples for String:String Function

Description

Create a function which returns the position of the rightmost occurrence of t in s, or -1 if there is none.

Demo Code

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

#define MAXLINE 1000/*from w  w  w. jav  a2 s. c o  m*/

int strindex(char source[], char searchfor[]);

int main(void)
{
    char source[MAXLINE] = "this is a test";
    char pattern[MAXLINE] = "test";

    printf("The position is: %d\n", strindex(source, pattern));

    return 0;
}
int strindex(char s[], char t[])
{
    int sl = strlen(s), tl= strlen(t);
    int i= sl - tl, j, k;
    int c;

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

Result


Related Tutorials