41 lines
863 B
C
41 lines
863 B
C
|
#include <stdio.h>
|
||
|
#include <string.h>
|
||
|
|
||
|
#define STRING "test string with lost of stuff"
|
||
|
|
||
|
int strindex(char source[], char searchfor[]);
|
||
|
|
||
|
/* pass optional searchfor arg to strindex with STRING, pretty print result */
|
||
|
int main(int argc, char *argv[])
|
||
|
{
|
||
|
char s[] = STRING;
|
||
|
char *t = (argc > 1) ? argv[1] : "est";
|
||
|
|
||
|
int i = strindex(s, t);
|
||
|
if (i < 0) {
|
||
|
printf("no match\n");
|
||
|
return 1;
|
||
|
}
|
||
|
|
||
|
printf("%s\n", s);
|
||
|
while (i--)
|
||
|
putchar(' ');
|
||
|
printf("^\n");
|
||
|
return 0;
|
||
|
}
|
||
|
|
||
|
/* strindex: return index of the righmost occurence of t in s, -1 if none */
|
||
|
int strindex(char s[], char t[])
|
||
|
{
|
||
|
int i, j;
|
||
|
const int tlen = strlen(t);
|
||
|
|
||
|
j = tlen - 1;
|
||
|
for (i = strlen(s)-1; i; i--)
|
||
|
if (s[i] != t[j])
|
||
|
j = tlen - 1;
|
||
|
else if (!(j--)) // match found
|
||
|
return i;
|
||
|
return -1;
|
||
|
}
|