Java Data Type How to - Find longest word in a sentence recursively








Question

We would like to know how to find longest word in a sentence recursively.

Answer

public class Main {
  public static String compare(String st1, String st2) {
    if (st1.length() > st2.length()) {
      return st1;
    } else {//from w w w.  j  a va  2 s  .  co  m
      return st2;
    }
  }

  public static void main(String[] args) {
    String str = "this is a test loooong test";
    String stringArray[] = str.split("\\s");

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