Skip to content

Instantly share code, notes, and snippets.

@Learath2
Created August 20, 2014 09:16
Show Gist options
  • Select an option

  • Save Learath2/5c134235293f5fafeb78 to your computer and use it in GitHub Desktop.

Select an option

Save Learath2/5c134235293f5fafeb78 to your computer and use it in GitHub Desktop.
K&R2 Exercise 4-1
/*K&R2 Exercise 4-1 "strindex"*/
#include <stdio.h>
#define MAX_LINE 1024
int getl(char[], int);
int strindex(char[], char[]);
char pattern[] = "ould";
int main()
{
char line[MAX_LINE];
int found = 0;
while(getl(line, MAX_LINE))
if(strindex(line, pattern) >= 0){
printf("%s", line);
found++;
}
return found;
}
int getl(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, m;
for(i = 0, m = -1; s[i] != '\0'; i++){
for(j = i, k = 0; s[j] == t[k]; j++, k++)
if(t[k] == '\0')
m = i;
}
return m;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment