Hi Yogesh,
I am trying to print the 2nd largest word in string but I could not able to do that. Please help me here.
Instructor
Yogesh Chawla Replied on 25/07/2021
See This. You can remove longest word function definition. That is just for reference.
package com.programming.class18;
import java.util.StringTokenizer;
public class SecondLargestWord {
public static void main(String[] args) {
String str = "Welcome to the family";
StringTokenizer st = new StringTokenizer(str);
System.out.println("Total number of tokens : " + st.countTokens());
String[] tokens = str.split(" ");
for (String element : tokens) {
System.out.println(element);
}
String longestWord = getLongestString(tokens);
String secondlongestWord = getSecondLongestString(tokens, longestWord);
System.out.println("Longest Word in Array is " + longestWord);
System.out.println("String Longest Word in Array is " + secondlongestWord);
}
public static String getLongestString(String[] array) {
int maxLength = 0;
String longestString = null;
for (String s : array) {
if (s.length() > maxLength) {
maxLength = s.length();
longestString = s;
}
}
return longestString;
}
public static String getSecondLongestString(String[] array, String longestWord) {
int maxLength = 0;
String secondlongestString = null;
for (String s : array) {
if (s.length() > maxLength && s.length() < longestWord.length()) {
maxLength = s.length();
secondlongestString = s;
}
}
return secondlongestString;
}
}
Thanks yogesh
Can you please explain the code by putting the comments