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

1 说明

在此程序中,我们需要找到字符串中最小和最大的单词:

Hardships often prepare ordinary people for an extraordinary destiny

考虑上面的示例,其中“an”是最小的词,而“extraordinary”是最大的词。查找最小和最大单词的方法之一是将字符串分成多个单词,然后将每个单词的长度与变量大小进行比较。如果单词的长度小于小单词的长度,则将该单词存储为小单词。如果单词的长度大于大单词的长度,则将该单词存储为大单词。

2 算法思路

  • 步骤1:开始
  • 步骤2: 定义String string="Hardships often prepare ordinary people for an extraordinary destiny"
  • 步骤3:定义word = " ", small = " ", large = " ".
  • 步骤4:将String []单词作为对象。
  • 步骤5:设定长度= 0
  • 步骤6:string = string + " "
  • 步骤7: SET i = 0。重复步骤8至9,直到i
  • 步骤8: IF(string.charAt(i)!='')然后
                  word = word + string.charAt(i)
                  else
                  word [length] = word
                  length = length + 1
                  word =“”
  • 步骤9: i = i + 1
  • 步骤10:small = large =words[0]
  • 步骤11: SET k =0。直到k重复步骤12至步骤14
  • 步骤12:如果IF(small.length()> words [k] .length()),
                  则
                  small = words [k]
  • 步骤13: IF(large.length()<words [k] .length())
                  然后
                  large = words[k]
  • 步骤14: k = k + 1
  • 第15步:打印small
  • 第16步:打印large
  • 步骤17:结束

3 程序实现

/**
 * 一点教程网: http://www.yiidian.com
 */
public class SmallestLargestWord    
   
  public static void main(String[] args){     
      String string = "Hardships often prepare ordinary people for an extraordinary destiny";    
      String word = "", small = "", large="";    
      String[] words = new String[100];    
      int length = 0;    
          
      //Add extra space after string to get the last word in the given string    
      string = string + " ";    
          
      for(int i = 0; i < string.length(); i++){    
          //Split the string into words    
          if(string.charAt(i) != ' '){    
              word = word + string.charAt(i);    
          }    
          else{    
              //Add word to array words    
              words[length] = word;    
              //Increment length    
              length++;    
              //Make word an empty string    
              word = "";    
          }    
      }            
      //Initialize small and large with first word in the string    
      small = large = words[0];    
          
      //Determine smallest and largest word in the string    
      for(int k = 0; k < length; k++){    
              
          //If length of small is greater than any word present in the string    
          //Store value of word into small    
          if(small.length() > words[k].length())    
              small = words[k];    
   
          //If length of large is less than any word present in the string    
          //Store value of word into large    
          if(large.length() < words[k].length())    
              large = words[k];    
      }    
      System.out.println("Smallest word: " + small);    
      System.out.println("Largest word: " + large);    
  }  }

以上代码输出结果为:

Smallest word: an
Largest word: extraordinary

 

热门文章

优秀文章