Advertisement
khalfella

ansi_c_pg065_ch04_ex01.c

Jan 1st, 2015
230
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.17 KB | None | 0 0
  1. /*
  2. * Exercise 4-1.
  3. * Write the function strindex(s,t) which returns the position of the rightmost
  4. * occurrence of t in s, or -1 if there is none.
  5. */
  6.  
  7. #include <stdio.h>
  8. #include <string.h>
  9.  
  10. #define MAXLINE 1000 /* maximum input line length */
  11.  
  12.  
  13. int get_line(char line[], int max);
  14. int strindex(char source[], char searchfor[]);
  15. char pattern[] = "ould"; /* pattern to search for */
  16. /* find all lines matching pattern */
  17.  
  18. int
  19. main()
  20. {
  21. char line[MAXLINE];
  22. int found = 0;
  23. while (get_line(line, MAXLINE) > 0)
  24. if (strindex(line, pattern) >= 0) {
  25. printf("%s", line);
  26. found++;
  27. }
  28. return (found);
  29. }
  30.  
  31. /* get_line: get line into s, return length */
  32. int
  33. get_line(char s[], int lim)
  34. {
  35. int c, i;
  36. i = 0;
  37. while (--lim > 0 && (c = getchar()) != EOF && c != '\n')
  38. s[i++] = c;
  39. if (c == '\n')
  40. s[i++] = c;
  41. s[i] = '\0';
  42. return (i);
  43. }
  44. /* strindex: return index of t in s, -1 if none */
  45. int
  46. strindex(char s[], char t[])
  47. {
  48. int i, j, k;
  49. i = strlen(s) - 1;
  50. for (i = strlen(s) - 1; i >= 0; i--) {
  51. for (j = i, k = 0; t[k] != '\0' && s[j] == t[k]; j++, k++)
  52. ;
  53.  
  54. if (k > 0 && t[k] == '\0')
  55. return (i);
  56. }
  57. return (-1);
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement