Reputation: 3
How to find the longest word in a string recursively?
Finished, thanks everyone. Here's the revised code.
public static String longestWord(String sentence)
{
String longest;
int i = sentence.indexOf(' ');
if (i == -1)
{
return sentence;
}
String first = sentence.substring(0,i);
first = first.trim();
String rest = sentence.substring(i);
rest = rest.trim();
longest = stringcompare(first,longestWord(rest));
return longest;
}
Upvotes: 0
Views: 9565
Reputation: 5546
First of all let's assume that the sentence string argument doesn't have any leading or trailing spaces. You are doing this for the recursive case by calling trim() which is sensible.
Then we need to define two cases, the base case and the recursive case.
The base case is where a space isn't found, i.e. the sentence passed in is just one word. In this case simply return the sentence.
In the recursive case we get the first word and the rest as you have done. Call longestWord on the rest of sentence. Then simply return the longest of the first word and whatever was returned by your recursive call.
Upvotes: 1
Reputation: 41
package com.kota.java;
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
*
* */
Upvotes: 1
Reputation: 718738
Hint 1:
Break the problem down into two parts:
Hint 2:
The problem is easier to solve if there are no leading and trailing spaces in the initial input string.
Upvotes: 1
Reputation: 4067
Try splitting the string using
String[] words = sentance.split(" ");
String longest = null;
String longestSize = 0;
for (String str: words) {
int size = str.length();
if (longestSize < size) {
longest = str;
longestSize = size;
}
}
Upvotes: 0