OpenJudge计算概论-文字排版

复制代码
/*======================================================================
文字排版
总时间限制: 1000ms 内存限制: 65536kB
描述
给一段英文短文,单词之间以空格分隔(每个单词应包括其前后紧邻的标点符号)。请将短文重新排版,要求如下: 
每行不超过80个字符;每个单词居于同一行上;在同一行的单词之间以一个空格分隔;行首和行尾都没有空格。

输入
第一行是一个整数n,表示英文短文中单词的数目. 其后是n个以空格分隔的英文单词(单词包括其前后紧邻的标点符号,且每个单词长度都不大于40个字母)。
输出
排版后的多行文本,每行文本字符数最多80个字符,单词之间以一个空格分隔,每行文本首尾都没有空格。
样例输入
84
One sweltering day, I was scooping ice cream into cones and told my four children they could "buy" a cone from me for a hug. Almost immediately, the kids lined up to make their purchases. The three youngest each gave me a quick hug, grabbed their cones and raced back outside. But when my teenage son at the end of the line finally got his turn to "buy" his ice cream, he gave me two hugs. "Keep the changes," he said with a smile.
样例输出
One sweltering day, I was scooping ice cream into cones and told my four
children they could "buy" a cone from me for a hug. Almost immediately, the kids
lined up to make their purchases. The three youngest each gave me a quick hug,
grabbed their cones and raced back outside. But when my teenage son at the end
of the line finally got his turn to "buy" his ice cream, he gave me two hugs.
"Keep the changes," he said with a smile.
========================================================================*/
复制代码

大概分三类情况做不同处理,详细分类如图所示:

复制代码
#include<stdio.h>
#include<string.h>
int main()
{
    int n,i;
    char a[45]={'\0'},b[85]={'\0'};//a数组是每次读取的一个单词(以空格分割的字符串),b数组是准备输出的一行(符合题目要求的字符串)。 
    int lenA=0,lenB=0;
    freopen("4.in","r",stdin);
    freopen("result.out","w",stdout);
    scanf("%d",&n);
    for(i=0;i<n;i++)
    {
        scanf("%s",a);
        lenA=strlen(a);
        if(lenB+1+lenA<79)
        {
            if(lenB>0)
                strcat(b," ");
            strcat(b,a);
            lenB=strlen(b);
        }
        else if(lenB+1+lenA==80||lenB+1+lenA==79)
        {
            printf("%s %s\n",b,a);
            lenB=0;
            b[0]='\0';//清空b数组的数据 
        }
        else //当lenB+1+lenA>80
        {
            printf("%s\n",b);
            strcpy(b,a);
            lenB=strlen(b);
        }
    }
    printf("%s\n",b);//前面的循环可能会使最后一行没输出并一直留在b数组里面 
    return 0;
}
复制代码

 

posted on   华山青竹  阅读(1357)  评论(0编辑  收藏  举报

编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示