1
1
/*
2
2
* Exercise 4-1. Write the function strindex(s,t) which returns the position of
3
- * the rightmost occurrence of s in t, or -1 if there is none.
3
+ * the rightmost occurrence of t in s, or -1 if there is none.
4
+ *
4
5
* By Faisal Saadatmand
5
6
*/
6
7
7
8
#include <stdio.h>
8
9
#include <string.h>
9
10
10
- #define MAXLINE 1000 /* maximum input line length */
11
+ #define MAXLEN 1000 /* maximum input line length */
11
12
12
13
/* functions */
13
14
int getLine (char [], int );
14
- int strindex (char [], char []);
15
-
16
- /* globals */
17
- char pattern [] = "ould" ; /* pattern to search for */
15
+ int strindex (char [], const char []);
18
16
19
17
/* getLine: get line into s, return */
20
18
int getLine (char s [], int lim )
@@ -34,32 +32,30 @@ int getLine(char s[], int lim)
34
32
}
35
33
36
34
/* strindex: return index of t in s, -1 if none */
37
- int strindex (char s [], char t [])
35
+ int strindex (char s [], const char t [])
38
36
{
39
37
int i , j , k ;
40
38
41
- for (i = strlen (s ); i >= 0 ; i -- ) { /* read the string backwards */
42
- for (j = i , k = 0 ; t [k ] != '\0' && s [j ] == t [k ]; j ++ , k ++ )
39
+ for (i = strlen (s ) - strlen ( t ) ; i >= 0 ; -- i ) {
40
+ for (j = i , k = 0 ; t [k ] != '\0' && s [j ] == t [k ]; ++ j , ++ k )
43
41
;
44
42
if (k > 0 && t [k ] == '\0' )
45
43
return i ;
46
44
}
47
-
48
45
return -1 ;
49
46
}
50
47
51
- /* find all lines matching pattern */
52
48
int main (void )
53
49
{
54
- char line [MAXLINE ];
55
- int found = 0 ;
56
- int position ;
50
+ char line [MAXLEN ];
51
+ const char pattern [] = "ould" ;
52
+ int pos ;
53
+
54
+ while (getLine (line , MAXLEN ) > 0 )
55
+ if ((pos = strindex (line , pattern )) < 0 )
56
+ printf ("Not found\n" );
57
+ else
58
+ printf ("%i\n" , pos );
57
59
58
- while (getLine (line , MAXLINE ) > 0 )
59
- if ((position = strindex (line , pattern )) >= 0 ) {
60
- printf ("%s" , line );
61
- printf ("%i\n" , position );
62
- found ++ ;
63
- }
64
- return found ;
60
+ return 0 ;
65
61
}
0 commit comments