Write a java program to check the longest word and shortest word in a string.Also check their lengths.
public class Test {
public static void main(String[] args) {
String str = "This, is";
Test t=new Test();
t.findLongAndShortWord(str);
}
public void findLongAndShortWord(String str){
str=str+" ";
String longestWord="";
String shortestWord="";
int maxLength=Integer.MIN_VALUE;
int minLength=Integer.MAX_VALUE;
String word="";
for(int i=0; i<str.length(); i++){
char ch=str.charAt(i);
if(Character.isWhitespace(ch)){
if(word.length()>maxLength){
longestWord=word;
maxLength =word.length();
}
if(word.length()<minLength){
shortestWord=word;
minLength =word.length();
}
word="";
}else if(Character.isLetter(ch)){
word+=ch;
}
}
System.out.println("longest word= "+longestWord+" length= "+longestWord.length());
System.out.println("shortest word= "+shortestWord+" length= "+shortestWord.length());
}
}
public class Test {
public static void main(String[] args) {
String str = "This, is";
Test t=new Test();
t.findLongAndShortWord(str);
}
public void findLongAndShortWord(String str){
str=str+" ";
String longestWord="";
String shortestWord="";
int maxLength=Integer.MIN_VALUE;
int minLength=Integer.MAX_VALUE;
String word="";
for(int i=0; i<str.length(); i++){
char ch=str.charAt(i);
if(Character.isWhitespace(ch)){
if(word.length()>maxLength){
longestWord=word;
maxLength =word.length();
}
if(word.length()<minLength){
shortestWord=word;
minLength =word.length();
}
word="";
}else if(Character.isLetter(ch)){
word+=ch;
}
}
System.out.println("longest word= "+longestWord+" length= "+longestWord.length());
System.out.println("shortest word= "+shortestWord+" length= "+shortestWord.length());
}
}
No comments:
Post a Comment