How do I print the second largest word in string array? | Core Java Forum
V
Vikrant Feddewar Posted on 25/07/2021

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.


Y
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;
	}

}

 


V
Vikrant Feddewar Replied on 25/07/2021

Thanks yogesh


V
Vijay Replied on 01/08/2021

Can you please explain the code by putting the comments