將長輸入行摺疊成若干較短的行

問題描述很簡單,就是限制每行的最大字符數量,若是超過了這個數,將多出來的部分摺疊到下一行,下一行照樣重複上述步驟,直到摺疊完畢。數組

這裏要考慮的問題有:函數

一、一旦判斷到當前讀取的字符數量已經到了限制值,我就要插入一個'\n'用來換行;oop

二、若是當前超過限制的位置是一個單詞的內部,好比說讀到「hello」這個單詞的'e'位時到了限制位,那麼不可能直接在這裏插入'\n'換行,怎麼辦?測試

結合上面的思考,咱們能夠設定三個臨時變量用來指明特定的數組下標:spa

一、current,指定當前讀取到的位置;3d

二、location,指定當前行讀取到的位置;code

三、spaceholder,指定當前找到的空格' '的位置。blog

在遍歷過程當中,current是要走徹底程的;location的最大值就是限制值(好比10),一旦完成一次摺疊,location將被重置爲0;而spaceholder則是記錄當前最新的有' '空格的位置,這樣咱們在摺疊時就不用擔憂會在詞彙中間插入'\n'換行而致使單詞被意外地分開。get

咱們能夠經過本身寫getline函數來收錄從stdin中輸入的字符。string

 1 //NeroHwang
 2 //2014-2-27
 3 
 4 #include <stdio.h>
 5 #include<assert.h>
 6 #define MAXLINE 1000
 7 const int MAXFOLD = 10; //Limit the max fold pos as 10
 8 int GetLine(char line[],int maxline);
 9 
10 int main(void)
11 {
12     //1,i_current,indicate the current index of the whole string.
13     //2,i_location,indicate the current pos in a line
14     int i_current,i_location;
15     int len;
16     int i_spaceHolder;       //Hold for the current pos which is a blank' '
17     char line[MAXLINE];
18     if((len = GetLine(line,MAXLINE)) >0)
19     {
20         if(len < MAXFOLD)
21         {
22             //do nothing
23         }
24         else
25         {
26             //there is some extra long lines
27             i_current = 0;
28             i_location = 0;
29             while(i_current < len)
30             {
31                 if(line[i_current] == ' ')
32                 {
33                     i_spaceHolder = i_current;
34                 }
35                 if(i_location == MAXFOLD)      //As soon as we find the pos needs to be folded...
36                 {
37                     line[i_spaceHolder] = '\n';
38                     i_location = 0;          //Reposition
39                 }
40                 ++i_current;
41                 ++i_location;
42             }
43         }
44         printf("%s\n",line);
45     }
46     return 0;
47 }
48 
49 int GetLine(char line[],int maxline)
50 {
51     assert(line != NULL && maxline <= MAXLINE && maxline >0);
52     char c;
53     int i;
54     //Atention Here.Don't use getchar twice in for loop.
55     for(i = 0; i <  maxline-1 && (c=getchar())!= EOF && c!= '\n'; ++i)
56     {
57         line[i] = c;
58     }
59     if(c =='\n')
60     {
61         line[i] = c;
62         ++i;
63     }
64     line[i] = '\0';
65     return i;
66 }

最後給出測試結果:

相關文章
相關標籤/搜索