Date: 2014dec16
Update: 2025sep21
Language: Java
Q. Java: Nice way to convert a String to title case
(First letter of each word capitalized)
A. Here is our function called toTitleCaseSimple() shown in a full example:
import java.text.BreakIterator;
class Demo {
// Helper function
static String ucFirstLowerRemainder(final String s) {
if (s == null) return "";
String first = "";
String remainder = "";
if (s.length() > 0) {
first = s.substring(0, 1);
}
if (s.length() > 1) {
remainder = s.substring(1);
}
return first.toUpperCase() + remainder.toLowerCase();
}
static String toTitleCaseSimple(final String s) {
BreakIterator wordBreaker = BreakIterator.getWordInstance();
StringBuilder out = new StringBuilder();
wordBreaker.setText(s);
int end = 0;
for (int start = wordBreaker.first(); (end = wordBreaker.next()) != BreakIterator.DONE; start = end) {
String word = s.substring(start, end); // `word` includes spaces
if (word.length() <= 2 && out.length() > 0) {
out.append(word.toLowerCase());
}
else {
out.append(ucFirstLowerRemainder(word));
}
}
return out.toString();
}
public static final void main(String []args) {
String out = toTitleCaseSimple("a tale of two cities");
System.out.println("out=" + out);
}
}
Output:
out=A Tale of Two Cities