《C程式設計語言》 練習1-22
- 2020 年 5 月 4 日
- 筆記
- C語言程式設計練習題
問題描述
練習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!='\n'; i++)
{
array[i] = c;
}
if (c=='\n')
{
array[i] = c;
i++;
}
array[i] = '\0';
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('\n');
sign=0;
pos = 0;
}
}else
{
pos++;
if (pos>MAX)
{
putchar('\n');
pos = 0;
}
putchar(array[i]);
sign=1;
}
}
pos = 0;
}
return 0;
}
運行結果


