将长输入行折叠成若干较短的行

问题描述很简单,就是限制每行的最大字符数量,若是超过了这个数,将多出来的部分折叠到下一行,下一行照样重复上述步骤,直到折叠完毕。数组

这里要考虑的问题有:函数

一、一旦判断到当前读取的字符数量已经到了限制值,我就要插入一个'\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 }

最后给出测试结果:

相关文章
相关标签/搜索