Skip to content

Commit 49ed777

Browse files
committed
minor tweaks
1 parent ff8a667 commit 49ed777

File tree

1 file changed

+17
-21
lines changed

1 file changed

+17
-21
lines changed

chapter04/4-1.c

+17-21
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,18 @@
11
/*
22
* 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+
*
45
* By Faisal Saadatmand
56
*/
67

78
#include <stdio.h>
89
#include <string.h>
910

10-
#define MAXLINE 1000 /* maximum input line length */
11+
#define MAXLEN 1000 /* maximum input line length */
1112

1213
/* functions */
1314
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 []);
1816

1917
/* getLine: get line into s, return */
2018
int getLine(char s[], int lim)
@@ -34,32 +32,30 @@ int getLine(char s[], int lim)
3432
}
3533

3634
/* 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[])
3836
{
3937
int i, j, k;
4038

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)
4341
;
4442
if (k > 0 && t[k] == '\0')
4543
return i;
4644
}
47-
4845
return -1;
4946
}
5047

51-
/* find all lines matching pattern */
5248
int main(void)
5349
{
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);
5759

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;
6561
}

0 commit comments

Comments
 (0)