K&R Exercise 1-9 (C)

后端 未结 30 1100
北荒
北荒 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:29

    Solution1: as per topics covered in the k&R book:

    #include 
    
    int main()
    {
        int c;
    
    while ((c = getchar()) != EOF)
        {
           if  (c == ' ') 
           {while ( getchar() == ' ' )
            ;  // ... we take no action
            }
    
            putchar(c);
    
        }
    
    return 0;
    }
    

    Solution2 : using program states:

    int main()
    {
        int c, nblanks = 0 ;
    
    while ((c = getchar()) != EOF)  
    {
       if (c != ' ')
           { putchar(c);
             nblanks = 0;}
    
       else if (c==' ' && nblanks == 0) // change of state
                {putchar(c);
                 nblanks++;}
    }
    return 0;
    }
    

    Solution3 : based on last seen char

    int main()
    {
    int c, lastc = 0;
    
    while ((c = getchar()) != EOF)
        {
            if ( c != ' ')
            {putchar(c);}
    
    
            if (c == ' ')
            {
                if (c==lastc)
                    ;
                else putchar(c);
    
            }
    
            lastc = c;
        }
    
    return 0;
    }
    

提交回复
热议问题