Skip to content

Instantly share code, notes, and snippets.

@giorgi568
Created August 10, 2024 17:30
Show Gist options
  • Select an option

  • Save giorgi568/d6cfd790d5e04931f17d9d05aeedfefa to your computer and use it in GitHub Desktop.

Select an option

Save giorgi568/d6cfd790d5e04931f17d9d05aeedfefa to your computer and use it in GitHub Desktop.
the c programming language, exercise 4-1
#include <stdio.h>
#include <string.h>
/*
code is from the book i only modified strindex,
which now returns rightmost occurrence of t in s
*/
#define MAXLINE 1000
int get_line(char line[], int max);
int strindex(char source[], char serachfor[]);
char pattern[] = "ould";
int main() {
char line[MAXLINE];
int found = 0;
while (get_line(line, MAXLINE) > 0) {
if(strindex(line, pattern) >= 0) {
printf("%s", line);
found++;
}
}
return found;
}
int get_line(char s[], int lim) {
int c, i;
i = 0;
while(--lim > 0 && (c = getchar()) != EOF && c != '\n'){
s[i++] = c;
}
if(c == '\n') {
s[i++] = c;
}
s[i] = '\0';
return i;
}
int strindex(char s[], char t[]) {
int i, j, k;
for(i = strlen(s) - 1; i > 0; --i) {
for(j=i, k=strlen(t)-1; k>0 && s[j]==t[k]; --j, --k)
;
if(k == 0) {
return i;
}
}
return -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment