Dave's Brain

Browse - Programming Tips - How can I convert a String to title case?

Date: 2014dec16
Language: Java

Q.  How can I convert a String to title case?
(First letter of each large word capitalized)

A.  Here is function for that.

import java.text.BreakIterator; // Helper function 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(); } 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(); }

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.