aboutsummaryrefslogtreecommitdiff
path: root/5.6.3.c
blob: a186c1f50c93843556e51e95f3a8371e2d7dcfe7 (plain) (blame)
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <stdio.h>

#define MAXLEN 1000

int get_line(char line[], const int max);
int strindex(char source[], char pattern[]);

int 
main(void)
{
  int found, rightmost;
  char line[MAXLEN];

  char pattern[] = "ould";
  found  = 0;

  while (get_line(line, MAXLEN) > 0)
    if ((rightmost = strindex(line, pattern)) >= 0) {
      printf("%s >> match at char %d\n", line, rightmost+1);
      found++;
    }

  printf("\nSneedGrep found %d match%s\n", found, (found > 0) ? "es" : "");

  return 0;
}

int 
get_line(char line[], const int max)
{
  int i;
  char input;

  for (i = 0; (input = getchar()) != EOF && input != '\n' && i < max-2; i++)
    line[i] = input;

  if (input == '\n' && i < max-2)
    line[i++] = '\n';

  line[i] = '\0';

  return i;
}

int 
strindex(char source[], char pattern[])
{
  int i, rightmost;
  char *source_og = source;

  rightmost = -1;

  for (; *source; source++) {
    for (i = 0; *(pattern +i) && *(source+i) == *(pattern+i); i++)
      ;

    if (!*(pattern+i))
      rightmost = source - source_og;
  }

  return rightmost;
}