C语言K&R习题系列——句子中一个空格代替多个空格的四种方法

来源:互联网 发布:联通网络信号差怎么办 编辑:程序博客网 时间:2024/05/22 08:25

原题:

Write a program to copy its input to its output, replacing each string of one or more blanks by a single blank.


第一种:

这种最常用,设置一个inspace作为布尔变量,标志当前输入是否在字符中,或在字符外


#include <stdio.h>  int main(void){  int c;  int inspace=0;    while((c = getchar()) != EOF)  {    if(c == ' ')    {      if(inspace == 0)      {        inspace = 1;        putchar(c);      }    }    else    {      inspace = 0;      putchar(c);    }  }    return 0;}


第二种:自己想的,虽然效果差不多,不过思路不一样

number作为标志位,记录空格的个数



 #include < stdio.h > main ( void ) {    int c;    int number;    number = 0;       //initialization space numbers           while ( ( c = getchar() ) != EOF )    {        if ( c == ' ' )        {            ++number;            if ( number == 1 )                putchar( c );        }        if ( c != ' ' )        {            putchar( c );            number = 0;        }    }    return 0; }


第三种:

使用一个while循环来“承接”多个空格


#include < stdio.h >main ( void ){    int c;    while ( ( c = getchar() ) != EOF )    {        if ( ' ' == c )        {            putchar ( c );            while ( ( c = getchar() ) == ' ' && c != EOF )                ;        }         if ( EOF == c )            break;         putchar ( c );    }    return 0;}


第四种:

使用一个字符pc作为“当前字符”之前的字符,通过pc来判断其后的空格是否输出


#include <stdio.h>int main(){        int c, pc;           pc = EOF;          while ((c = getchar()) != EOF) {                if (c == ' ')                        if (pc != ' ')                                   putchar(c);                  if (c != ' ')                        putchar(c);                pc = c;        }          return 0;}



1 0