1.8
#include <stdio.h>
int main(){
int c;
int space = 0;
int tab = 0;
int nextline = 0;
while((c=getchar())!=EOF){
switch(c){
case ' ':
space++;
break;
case '\n':
nextline++;
break;
case '\t':
tab++;
break;
default:
break;
}
}
printf("space=%d, tab=%d, nextline=%d\n", space, tab, nextline);
}
1.9
/* 解法一*/
#include <stdio.h>
#include <stdbool.h>
#include <ctype.h>
int main(){
int c;
bool flag = false;
while((c = getchar()) != EOF){
if(isalnum(c)){
flag = true;
printf("%c", c);
} else if(' ' == c && flag){
flag = false;
printf("%c", ' ');
}
}
return 0;
}
/*第二种解法*/
#include <stdio.h>
#define NOBLANK 'a'
/*replace string of blanks with a single blank*/
int main(){
int c, lastc;
lastc = NOBLANK;
while((c = getchar()) != EOF){
if(' ' != c){
putchar(c);
} else if(lastc != ' '){
putchar(c);
}
lastc = c ;
}
}
1.10
#include <stdio.h>
int main(){
int c;
while((c = getchar()) != EOF){
switch(c){
case '\t':
printf("\\t");
break;
case '\b':
printf("\\b");
break;
case '\\':
printf("\\\\");
break;
default:
printf("%c", c);
break;
}
}
return 0;
}
1.11
略
1.12
/*解法一*/
#include <stdio.h>
void display(char s[]);
int main(){
char s[128];
printf("Please a string you want print: ");
fgets(s, 127, stdin);
display(s);
printf("%s", s);
return 0;
}
void display(char s[]){
int i = 0;
int j = 0;
char lastc = 'a';
for(i = 0; s[i] != '\0'; i++){
if(s[i] != ' '){
s[j++] = s[i];
} else if(lastc != '\n' && lastc != ' '){
s[i] = '\n';
s[j++] = s[i];
}
lastc = s[i];
}
s[j] = '\0';
}
/*解法二*/
#include <stdio.h>
#define IN 1 /* inside a word*/
#define OUT 0 /*outside a word*/
/*print input one word per line*/
int main(){
int c , state;
state = OUT;
while((c = getchar()) != EOF){
if(c == ' ' || c == '\n' || c == '\t'){
if(state == IN){
putchar('\n');
state = OUT;
}
} else if(state == OUT){
state = IN;
putchar(c);
} else {
putchar(c);
}
}
}