K&R Exercise 1-9 (C)

后端 未结 30 1103
北荒
北荒 2021-01-31 19:46

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

I\'m assuming by thi

相关标签:
30条回答
  • 2021-01-31 20:10
    1.Count the number of blanks.
    2.Replace the counted number of blanks by a single one.
    3.Print the characters one by one.
    
    <code>
    main()
    {
        int c, count;
        count = 0;
        while ((c = getchar()) != EOF)
        {
            if (c == ' ')
            {
                count++;
                if (count > 1) 
                {
                    putchar ('\b');
                    putchar (' ');
                }
                else putchar (' ');
            }
            else 
            {
                putchar (c);
                count = 0;
            }
        }
        return;
    }
    </code>
    
    0 讨论(0)
  • 2021-01-31 20:11
    for(nb = 0; (c = getchar()) != EOF;)
    {
        if(c == ' ')
           nb++;
        if( nb == 0 || nb == 1 )
           putchar(c);
        if(c != ' '  &&  nb >1)
           putchar(c);
        if(c != ' ')
           nb = 0;
     }
    
    0 讨论(0)
  • 2021-01-31 20:16

    This is what I got:

    while ch = getchar()
       if ch != ' '
          putchar(ch)
       if ch == ' '
          if last_seen_ch != ch
             putchar(ch)
       last_seen_ch = ch
    
    0 讨论(0)
  • 2021-01-31 20:17

    Since relational operators in C produce integer values 1 or 0 (as explained earlier in the book), the logical expression "current character non-blank or previous character non-blank" can be simulated with integer arithmetic resulting in a shorter (if somewhat cryptic) code:

    int c, p = EOF;
    while ((c = getchar()) != EOF) {
        if ((c != ' ') + (p != ' ') > 0) putchar(c);
        p = c;
    }
    

    Variable p is initialized with EOF so that it has a valid non-blank value during the very first comparison.

    0 讨论(0)
  • 2021-01-31 20:18

    I wrote this and seems to be working.

     # include <stdio.h>
     int main ()
    {
    
    int c,lastc;
    lastc=0;
    while ((c=getchar()) != EOF)
        if (((c==' ')+ (lastc==' '))<2)
            putchar(c), lastc=c;
     }
    
    0 讨论(0)
  • 2021-01-31 20:18

    First declare two variables character and last_character as integers.when you have not reach the end of the file( while(character=getchar() != EOF ) do this; 1. If character != ' ' then print character last_character = character 2. If character == ' ' if last_character ==' ' last character = character else print character

    0 讨论(0)
提交回复
热议问题