Chinaunix首页 | 论坛 | 博客
  • 博客访问: 222473
  • 博文数量: 136
  • 博客积分: 2919
  • 博客等级: 少校
  • 技术积分: 1299
  • 用 户 组: 普通用户
  • 注册时间: 2011-03-11 09:08
文章分类

全部博文(136)

文章存档

2013年(1)

2011年(135)

我的朋友

分类: C/C++

2011-03-21 10:18:19

  1. /* k&r(4.1): Basic of Functions
  2.    created on Mar 21, 2011
  3.  */

  4. # include <stdio.h>
  5. # include <string.h>
  6. /* analysis: the job fall neatly into three pieces:
  7.    * while (there's another line)
  8.           if (the line contains the pattern)
  9.          print it
  10. */
  11. #define MAXLINE 1000 /* maximum input line length */
  12. int mgetline(char line[], int max);
  13. int strindex(char source[], char searchfor[]);

  14. /* main: print each line of its input that contains a pattern */
  15. int main()
  16. {
  17.     char line[MAXLINE];
  18.     int found = 0;
  19.     printf("The length of line is %d\n", strlen(line));
  20.     char pattern[] = "ould"; /* pattern to search for */
  21.     while (mgetline(line, MAXLINE) > 0 )
  22.      if (strindex(line, pattern) >= 0) {
  23.          printf("%s", line);
  24.          found++;
  25.     }

  26.     return found;
  27. }

  28. /* getline: get line into s, return length */
  29. int mgetline(char s[], int lim)
  30. {
  31.     int c, i;

  32.     i = 0;
  33.     /* or use while like this:
  34.      * while (--lim > 0 && (c=getchar()) != EOF && c != '\n')
  35.      s[i++] = c;
  36.      */
  37.     for (i = 0; (c = getchar()) != EOF && '\n'; ++i)
  38.      s[i] = c;
  39.     
  40.     if (c == '\n')
  41.      s[i++] = c;
  42.     s[i] = '\0';
  43.     return i;
  44. }

  45. /* strindex: return index of t in s, -1 if none */
  46. int strindex(char s[], char t[])
  47. {
  48.     int i, j, k;

  49.     for (i = 0; s[i] != '\0'; i++) {
  50.         for (j = i, k = 0; t[k]!='\0' && s[j] == t[k]; j++, k++)
  51.          ;
  52.         if (k > 0 && t[k] == '\0')
  53.          return i;
  54.     }
  55.     return -1;
  56. }
阅读(465) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~