C 删除输入中多余空格
做到这样一题,是将其中多个空格替换为一个空格,回想起来PHP也有类似需求,暂时先mark一下这个方法。
我的想法是根据空格前面是否存在空格来控制空格的输出。(书中答案貌似更简练一些,直接加一个变量记录这次输出的值,用那个值来对比)
1#include <stdio.h>
2
3int space = 0;
4
5int c;
6
7main(void)
8{
9 while ((c = getchar()) != EOF) {
10 if (c == ' ' && !space) {
11 space = 1;
12 putchar(c);
13 } else if (c != ' ') {
14 space = 0;
15 putchar(c);
16 }
17 }
18
19 return 0;
20}
21
PHP中可以用转为数组-删除数组空白元素-转为字符串的方法,首尾部分空格可以用trim()
处理
评论 (0)