How to Find the Longest Word in String in Java

This is the simple and interesting java programming exercise on string. The java program will find out the largest words in a given strings e.g. "I am Listening" the longest word will be "Listening".


Source Code 

package packaga;
public class longestWord {
/**
     * @param args the command line arguments
     */
public static void main(String[] args) {
String str="Example String to test";
String greatest="";
int s=str.length(),wordSize=0;
String[] wordsCollecton=str.split(" "); // Splits the "Hello pak world" in to 3 words [ Hello , pak , world ]
for(String tempWord:wordsCollecton)//iterate for each word
{
if(tempWord.length()>wordSize)//find the greater word
{
greatest=tempWord;//stores the greater word
wordSize = tempWord.length();//stores the size
}
}
System.out.println("Longest Word is \""+greatest+"\" in String \""+str+"\"");
}
}

Output of the Program

Find the Longest Word in String in Java

Share on Google Plus

About Asad

Asad Niazi is Software Engineer , Programmer, Web Developer and a young mentor of BloggersTown and PProgramming. Asad Love to writes about Technology, Programming, Blogging and make money online.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment