Java 程序查找字符串中的最大和最小单词。

2025 年 1 月 8 日 | 3 分钟阅读

在此程序中,我们需要查找字符串中存在的最短和最长的单词。

艰难困苦常常会为平凡的人们,带来不平凡的命运。

考虑上面的例子,其中“ an ”是最短的单词,“ extraordinary ”是最长的单词。查找最短和最长单词的一种方法是将字符串拆分为单词,然后比较每个单词的长度与变量 small 和 large。如果一个单词的长度小于 small 的长度,则将该单词存储在 small 中。如果一个单词的长度大于 large 的长度,则将该单词存储在 large 中。

算法

  • 步骤 1: 开始
  • 步骤 2: 定义 String string="Hardships often prepare ordinary people for an extraordinary destiny"
  • 步骤 3: 定义 word = " ", small = " ", large = " "。
  • 步骤 4: 创建 String[] words 对象。
  • 步骤 5: 设置 length =0
  • 步骤 6: string = string + " "
  • 步骤 7: 设置 i=0。重复步骤 8 至 9,直到 i
  • 步骤 8: IF(string.charAt(i) != ' ') then
                  word =word + string.charAt(i)
                  else
                  word[length]=word
                  length =length + 1
                  word = " "
  • 步骤 9: i=i+1
  • 步骤 10: small = large =words[0]
  • 步骤 11: 设置 k = 0。重复步骤 12 至步骤 14,直到 k
  • 步骤 12: IF(small.length() > words[k].length())
                  then
                  small = words[k]
  • 步骤 13: IF(large.length() < words[k].length())
                  then
                  large = words[k]
  • 步骤 14: k = k + 1
  • 步骤 15: 打印 small
  • 步骤 16: 打印 large
  • 步骤 17: 结束

程序

输出

Smallest word: an
Largest word: extraordinary
下一个主题Java 程序