forked from wzqnls/The-C-Programming-Language-Exercises
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path4-1.c
More file actions
37 lines (29 loc) · 678 Bytes
/
4-1.c
File metadata and controls
37 lines (29 loc) · 678 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/* 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>
int strindex(char s[], char t[]);
int main()
{
printf("strindex(\"asdfsshitasdfshitasa\", \"shit\") -> %d\n", strindex("asdfsshitasdfshitasa", "shit"));
return 0;
}
int strindex(char s[], char t[])
{
int len_s = strlen(s);
int len_t = strlen(t);
int i, j, k;
for (i = len_s - len_t - 1; i >= 0; i--)
{
for (j = 0, k = i; t[j] != '\0' && t[j] == s[k]; j++, k++)
;
if (j > 0 && t[j] == '\0')
{
return i;
}
}
return -1;
}