Wednesday, 25 July 2012

Finding the longest word in a user given string ..!

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package com.kota.core;
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();
 }
}
/**
 * Out put : Longest word = intelligent
 * 
 * */

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...