This is the first solution to find the maximum and minimum length strings from a given input sentence of strings, using the core logic.
import java.util.Scanner;
import java.util.StringTokenizer;
public class MinandMaxLengthStrings {
public static void main(String args[]) {
@SuppressWarnings("resource")
Scanner inpStr=new Scanner(System.in);
String sentence=inpStr.nextLine();
System.out.println("The given sentence is="+sentence);
StringTokenizer wordsOfsentence=new StringTokenizer(sentence);
//Initialize the max and min variable
int max=0,min=sentence.length();
String maxLenStr = null;
String minLenStr = null;
//Process each word of the given sentence and check the length of each word against min and max variables
while (wordsOfsentence.hasMoreTokens()) {
String eachWord=wordsOfsentence.nextToken();
if (eachWord.length() > max){
max=eachWord.length();
maxLenStr=eachWord;
}
if (eachWord.length() < min) {
min=eachWord.length();
minLenStr=eachWord;
}
}
System.out.println("The maximum Length String is="+maxLenStr+" and the minimum Length String is="+minLenStr);
}
}
OUTPUT:
This is real technical interview
The given sentence is=This is real technical interview
The maximum Length String is=interview and the minimum Length String is=is

Leave a comment