代码参考:《K&R》
1、单词计数
#include<stdio.h> #define IN 1 #define OUT 0 main() { int c, state; int nword; nword = 0; state = OUT; while((c = getchar()) != EOF){ if(c == ' ' || c == ' ' || c == ' ') state = OUT; else if(state == OUT){ state = IN; ++ nword; } } // 可以用集合里的Vn图理解, 每次循环都有三种情况。 printf("%d ", nword); }
2、统计数字、空白符及其他字符
#include<stdio.h> main() { int c, i, nwhite, nother, ndigit[10]; nwhite = nother; for(i = 0; i < 10; i ++) ndigit[i] = 0; while((c = getchar()) != EOF){ switch(c){ case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': ndigit[c-'0'] ++; break; case ' ': case ' ': case ' ': nwhite ++; break; default: nother ++; break; } } printf("digits ="); for(i = 0; i < 10; i ++) printf(" %d", ndigit[i]); printf(", white space = %d, other = %d ", nwhite, nother); return 0; }
3、找指定具有指定模式的行
#include<stdio.h> #define MAXLINE 1000 int getline(char line[], int max); int strindex(char source[], char searchfor[]); char pattern[] = "ould"; main() { char line[MAXLINE]; int found = 0; while(getline(line , MAXLINE) > 0) if(strindex(line , pattern) >= 0){ printf("%s", line); found++; } return found; } int getline(char s[], int lim) { int c, i; i = 0; while(--lim > 0 && (c=getchar()) != EOF && c != ' ') s[i++] = c; if(c == ' ') s[i++] = c; s[i] = '