手抄代碼1-19

1-19

將輸入的行,倒置。函數

#include <stdio.h>
#define MAXLINE 1000//最大行長

int getlin(char line[], int maxline);//輸入行返回串長
void reverse(char line[]);//字符串倒置處理

main()
{
    char line[MAXLINE];
    while (getlin(line, MAXLINE)>0) {
        reverse(line);
        printf("%s", line);
    }
}

int getlin(char line[], int maxline)
{
    int c, i;
    for(i=0;(c=getchar())!='\n' && i<maxline;i++)//行是否結束。
    {
        line[i] = c;
    }
    if(c=='\n')
        line[i++] = '\n';
    line[i] = '\0';//字符串。
    return i;
}

void reverse(char line[])
{
    int i, j, c;
    i = j = 0;
    while (line[i] != '\0') {//找到尾
        i++;
    }
    if(line[--i]=='\n')
        i--;
    while (j<i) {//頭尾對調
        c = line[j];
        line[j] = line[i];
        line[i] = c;
        i--;
        j++;
    }
}

//拆分合理。實現函數,main組織函數。code

1-20

實現set功能,不對稱插入。字符串

#include <stdio.h>
#define TABLNC 8
main()
{
    int c, nb, pos;
    nb = 0;//要打印的空格數。
    pos = 1;//不要打印的空格數
    /*
     程序是這樣的,
     把全部行,切成諾幹個小塊(8個字符),
     在含有tab符小塊的地方,缺乏的部分用空格填充。
     如:abcd\t123; 變成abcd , , , ,123;由於abcd佔了4個位置。
     */
    while ((c=getchar()) != EOF) {
        if(c == '\t')
        {
            nb = TABLNC-(pos-1)%TABLNC;//運到tab,把行劃分紅塊,8-多出的字符,等於空格數。
            while (nb>0) {//pos-1是技巧。處理了‘\n’;
                putchar(' ');
                pos++;
                nb--;
            }
        }
        else if (c == '\n') {//進入新行,
            putchar(c);
            pos = 1;
        }
        else
        {
             putchar(c);
             pos++;
        }
    }
    printf("%d\n", 0/8);
}

換行是沒有佔位的。因此要過濾掉。get

相關文章
相關標籤/搜索