《C程序设计语言》 练习1-22

问题描述

  练习1-22 编写一个程序,把较长的输入行“折”成短一些的两行或者多行,折行的位置在输入行的第N列之前的最后一个非空格之后。要保持程序能够智能地处理输入行很长以及在制定的列前没有空格或者制表符时的情况。

  Write a program to "fold" long input lines into two or more shorter lines after the last non-blank character that occurs before the n-th column of input. Make sure your program does something intelligent with very long lines, and if there are no blanks or tabs before the specified column.

解题思路

  我写的程序和答案有些出入,标准答案我大致浏览了一下,感觉很麻烦,所以下面的代码是我自己的思路,并且运行结果符合题目要求

  首先,我们先来分析一下题目要求:

1.把长行分成两行或几行,例如把10个a,分成两行5个a

aaaaaaaaaa
变成:
aaaaa
aaaaa

2.把空格分开的同一行的几段分为几行:

11111              22222     33333
分为:
11111
22222
33333 

 

  了解了题目要求后,我们知道要规定一个值,当字符串长度大于这个值之后要分行,还有,遇到第一个空格要分行。

代码如下

#include<stdio.h>
#define MAXLEN 1024
#define MAX 10//字符串长度大于这个值后要分行

int getlines(int array[] , int maxlen);//将输入读入数组,并且在回车后输出结果

int getlines(int array[] , int maxlen)
{
    int c,i;
    for ( i = 0; i < maxlen-1 && (c=getchar())!=EOF && c!='
'; i++)
    {
        array[i] = c;
    }
    if (c=='
')
    {
        array[i] = c;
        i++;
    }
    array[i] = '';
    return i;
}

int main()
{
    int array[MAXLEN];
    int len;
    int i;
    int sign=1;//若是第一个空格,值为1,否则为0
    int pos=0;//连续字符个数计数器
    while ((len=getlines(array , MAXLEN)) > 0)
    {
        for(i = 0 ; i < len ; i++)
        {
            if (array[i]==' ')
            {
                if (sign==1)
                {
                    putchar('
');
                    sign=0;
                    pos = 0;
                }
            }else
            {
                pos++;
                if (pos>MAX)
                {
                    putchar('
');
                    pos = 0;
                }
                    
                putchar(array[i]);
                sign=1;
                
            }
        }
        pos = 0;
    }
    return 0;
}

  

运行结果

 

原文地址:https://www.cnblogs.com/jerryleesir/p/12827973.html