鱼C论坛

 找回密码
 立即注册
查看: 1611|回复: 0

[技术交流] 按照原文本中的顺序输出最短和最长的字符串

[复制链接]
发表于 2020-2-28 14:44:05 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
输入包括多行字符串,字符串的长度len(1<=len<=1000)。按原文本中的顺序输出其中最短和最长的字符串,如果最短和最长的字符串不止一个,全部输出。

例:
          输入:
  1. hello
  2. she
  3. sorry
  4. he
复制代码
         输出:
  1. he
  2. hello
  3. sorry
复制代码
有一点要注意的就是没有说字符串有没有空格,所以不用scanf输入字符串,用gets函数。
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>

  4. typedef struct String
  5. {
  6.     char str[1000];
  7.     int length;
  8. }String;

  9. String strings[100];        //假设最多100个字符串

  10. int main()
  11. {
  12.     char ch;
  13.     //char longest[1000] = {0}, shortest[1000] = {0};
  14.     int i = 0;
  15.     while(gets(strings[i].str))//字符串可能有空格,所以不能用scanf,用gets接收
  16.     {
  17.         strings[i].length = strlen(strings[i].str);
  18.         i++;
  19.     }//一共输入了i个字符串
  20.     int l, s;
  21.     l = s = strings[0].length;//初始化最长最短字符串的长度
  22.     int count_short[100] = {0}, count_long[100] = {100};//记录最长最短字符串的位置
  23.     int count_s = 0, count_l = 100;//最长最短字符串的标记位置
  24.     for(int j = 1; j < i; j++)
  25.     {
  26.         if(strings[j].length > l)//找到了比最长字符串更长的
  27.         {
  28.             count_l++;
  29.             count_long[j] = count_l;
  30.             l = strings[j].length;
  31.         }
  32.         else if(strings[j].length < s)//找到了比最短字符串更短的
  33.         {
  34.             count_s++;
  35.             count_short[j] = count_s;
  36.             s = strings[j].length;
  37.         }
  38.         else if(strings[j].length == l)//找到了与最长字符串等长的
  39.         {
  40.             count_long[j] = count_l;
  41.         }
  42.         else if(strings[j].length == s)//找到了与最短字符串等长的
  43.         {
  44.             count_short[j] = count_s;
  45.         }
  46.     }//循环结束时count_s和count_l记录的是最短最长字符串的标记位置
  47.     for(int k = 0; k < i; k++)
  48.     {
  49.         if(count_short[k] == count_s)
  50.             printf("%s\n", strings[k].str);
  51.     }
  52.     for(int k = 0; k < i; k++)
  53.     {
  54.         if(count_long[k] == count_l)
  55.             printf("%s\n", strings[k].str);
  56.     }
  57.    
  58.     return 0;
  59. }
复制代码
之所以将count_s和count_l设置成0和100,是为了防止输出时的识别错误导致输出错误。


其实我设置的tag有点多,没有必要设置这么多tag


小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-7-13 10:09

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表