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

 
 

Share on Google+Share on Google+
Find Longest Word from the string using Java
Posted on: October 24, 2009 at 12:00 AM
Advertisement
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
Advertisement

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


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: October 24, 2009

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com