We can start by basing our function off of strindex
.
/* strindex: return index of t in s, -1 if none */
int strindex(char s[], char t[])
{
int i, j, k;
for (i = 0; s[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;
}
In strindex
, i starts as zero and increments if
t is not found starting from i, which means it
returns the leftmost occurence. In order to return the rightmost, we
need to set i to equal the index of the last character of
s, and decrement it after every iteration. Additionally, we
need to make sure that we also exit the loop if
s[j] == '\0'
since that is now also a possible occurrence
as i starts off as the length instead.
/* strindex: return index of t in s, -1 if none */
int strindex(char s[], char t[])
/* strrindex: return rightmost index of t in s, -1 if none */
int strrindex(char s[], char t[])
{
int i, j, k;
for (i = 0; s[i] != '\0'; ++i)
;
while (--i >= 0) {
for (j=i, k=0; s[j]!='\0' && t[k]!='\0' && s[j]==t[k]; j++, k++)
;
if (k > 0 && t[k] == '\0')
return i;
}
return -1;
}
Note: inside the while
-loop, the prefix decrement
operator is used because initially, i is equal to the index
of \0
in s.