Home Tutorial Java Core Find Longest Word from the string using Java

 
 

Find Longest Word from the string using Java
Posted on: October 24, 2009 at 12:00 AM
In this section, you will learn how to get the longest word from the string using Java Programming.

Find Longest Word from the string using Java

Here we are going to find the longest word from the string. For this, we have specified the string which is then splitted into string array using  split() method. Then we have created a method compare(String st1,String st2)  that will compare the two strings and allow the longest word to display.

Here is the code:

import java.util.*;

class LongestWord
{
String str = "Ram is intelligent boy";
String stringArray[] = str.split("\\s");
public String compare(String st1, String st2){
if(st1.length()>st2.length()){
return st1;
}
else{
return st2;
}
}
LongestWord(){
String word = "";
for(int i=0;i<stringArray.length;i++){
if(i==0){
word = stringArray[0];
}
word = compare(word, stringArray[i]);
}
System.out.println("Longest word = " + word);
}
public static void main(String []args){
new LongestWord();
}
}

Output:

Longest word=intelligent

Related Tags for Find Longest Word from the string using Java:


Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.