I have done it finally like what I want. Thank you all for helping and I want to emphasize that it was NOT homework.
public static void main(String[] args) {
String input = "Java is a programming language";
StringTokenizer st = new StringTokenizer(input);
System.out.print(longestWord(input));
}
public static String longestWord(StringTokenizer st) {
if (!st.hasMoreTokens()) {
return "";
} else {
String token = st.nextToken();
String longestInTheRest = longestWord(st);
if (token.length() > longestInTheRest.length()) {
return token;
} else {
return longestInTheRest;
}
Another solution, written in a more functional style - notice that I'm not allocating new strings in each call to the recursive method (only the
split
operation at the beginning allocates new strings). I also took Robert's suggestion of first converting the original problem into a recursion over arrays, it makes things simpler:The trick in the above solution, is that my recursion advances over the indexes of the string array, and not over the strings themselves. That's the reason why I avoid creating new strings at each call. No
substring
,copyOfRange
,arraycopy
,new String()
or similar operations are needed, yielding a more elegant solution.EDIT:
I simplified the above code a little, to make it easier to understand. With regard to the
split
method it's a standard string operation, take a look at the documentation.