Capitalize each word in a sentence with recursive function in Java
Description
The following code shows how to capitalize each word in a sentence with recursive function.
Example
// w w w .jav a 2 s . c om
public class Main {
public static void main(String[] args) {
String sentence = "this is a test from java2s.com";
System.out.println(capSentence(sentence, true));
}
public static String capSentence(String string, boolean capitalize) {
if (string.length() == 0) {
return "";
}
String c = string.substring(0, 1);
if (capitalize) {
return c.toUpperCase() + capSentence(string.substring(1), c.equals(" "));
} else {
return c.toLowerCase() + capSentence(string.substring(1), c.equals(" "));
}
}
}
The code above generates the following result.
Home »
Java Tutorial »
Java Data Type »
Java Tutorial »
Java Data Type »