代码参考:《K&R》
1、单词计数
#include<stdio.h> #define IN 1
#define OUT 0 main()
{
int c, state;
int nword; nword = ;
state = OUT;
while((c = getchar()) != EOF){
if(c == ' ' || c == '\n' || c == '\t')
state = OUT;
else if(state == OUT){
state = IN;
++ nword;
}
} // 可以用集合里的Vn图理解, 每次循环都有三种情况。
printf("%d\n", nword);
}
2、统计数字、空白符及其他字符
#include<stdio.h> main()
{
int c, i, nwhite, nother, ndigit[]; nwhite = nother;
for(i = ; i < ; i ++)
ndigit[i] = ;
while((c = getchar()) != EOF){
switch(c){
case '': case '': case '': case '': case '': case '': case '': case '': case '': case '':
ndigit[c-''] ++;
break;
case ' ':
case '\n':
case '\t':
nwhite ++;
break;
default:
nother ++;
break;
}
}
printf("digits =");
for(i = ; i < ; i ++)
printf(" %d", ndigit[i]);
printf(", white space = %d, other = %d\n", nwhite, nother);
return ;
}
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 = ; while(getline(line , MAXLINE) > )
if(strindex(line , pattern) >= ){
printf("%s", line);
found++;
}
return found;
} int getline(char s[], int lim)
{
int c, i; i = ;
while(--lim > && (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; for(i = ; s[i] != '\0'; i ++){
for(j=i, k=; t[k]!='\0' && s[j]==t[k]; j++, k++)
;
if(k > && t[k] == '\0')
return i;
}
return -;
}
实际在控制台界面运行时,是输入一行判断一行的,最后用Ctrl+Z结束。