Java查找字符串中最大和最小的单词
在此程序中,我们需要找到字符串中存在的最小和最大的单词:
考虑到上面的例子,"an"是最小的词,而"extraordinary"是最大的词。查找最小和最大单词的方法之一是将字符串拆分为单词,然后将每个单词的长度与变量大小进行比较。如果单词的长度小于小单词的长度,则将该单词存储为小单词。如果单词的长度大于大单词的长度,则将该单词存储为大单词。
算法
步骤1: START
步骤2: DEFINE String string ="Hardships often prepare ordinary people for an extraordinary destiny"
步骤3: 定义word = " ", small = " ", large = " "。
步骤4: 将SString[] words作为对象。
步骤5: SET length = 0
步骤6: string = string + " "
步骤7: SET i = 0。重复步骤8至9
步骤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: 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
STEP 16: 打印large
STEP 17: END
程序:
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