Are there any built in methods available to convert a string into Title Case format?
-
7Everyone reading this question: beware that many of the top voted answers here DO NOT WORK PROPERLY for all languages. You need an i18n-aware library for correct titlecasing, like ICU4J (see Daniel F's answer). – sffc Nov 29 '18 at 23:26
-
Does this answer your question? [How to capitalize the first character of each word in a string](https://stackoverflow.com/questions/1892765/how-to-capitalize-the-first-character-of-each-word-in-a-string) – M. Justin Dec 14 '22 at 19:52
-
I take back my duplicate question. That is specifically not title case, in that it leaves the case of non-initial letters of each word alone, rather than changing them to upper case. e.g. aBcD -> "ABcD", not "Abcd". – M. Justin Jul 11 '23 at 17:46
22 Answers
Apache Commons StringUtils.capitalize() or Commons Text WordUtils.capitalize()
e.g: WordUtils.capitalize("i am FINE") = "I Am FINE"
from WordUtils doc

- 3,837
- 1
- 36
- 46

- 12,815
- 8
- 45
- 68
-
19WordUtils.capitalizeFully() was better for me as it gives: WordUtils.capitalizeFully("i am FINE") = "I Am Fine" – theINtoy Jul 22 '15 at 14:29
-
3Just a small update, WordUtils is gone to Commons Text and is deprecated inside Commons Lang – msrd0 Oct 16 '17 at 21:45
-
2
-
-
1**2021**: `WordUtils` in Apache Commons is deprecated now. _Use StringUtils_ – singh.rbir May 08 '21 at 18:28
There are no capitalize() or titleCase() methods in Java's String class. You have two choices:
- using commons lang string utils.
StringUtils.capitalize(null) = null
StringUtils.capitalize("") = ""
StringUtils.capitalize("cat") = "Cat"
StringUtils.capitalize("cAt") = "CAt"
StringUtils.capitalize("'cat'") = "'cat'"
- write (yet another) static helper method toTitleCase()
Sample implementation
public static String toTitleCase(String input) {
StringBuilder titleCase = new StringBuilder(input.length());
boolean nextTitleCase = true;
for (char c : input.toCharArray()) {
if (Character.isSpaceChar(c)) {
nextTitleCase = true;
} else if (nextTitleCase) {
c = Character.toTitleCase(c);
nextTitleCase = false;
}
titleCase.append(c);
}
return titleCase.toString();
}
Testcase
System.out.println(toTitleCase("string"));
System.out.println(toTitleCase("another string"));
System.out.println(toTitleCase("YET ANOTHER STRING"));
outputs:
String Another String YET ANOTHER STRING
-
1This is a nice little routine, but it fails for the more general case in which Strings may represent names. In this case, capitalization would also need to occur after apostrophes and hyphens, too. Eg. O'Connor and J. Wilkes-Booth. Of course, other languages may have additional title case rules. – scottb Apr 01 '13 at 02:43
-
1...If it were going to include that, wouldnt it need an entire dictionary lookup just to work out if the current word was a name? That seems a bit much for any one method. – MMJZ Jun 10 '15 at 14:39
-
This code is almost fine because some names can have prepositons such as de, del, della, dei, da as in Maria del Carmen, Maria da Silva, Maria della Salute, etc. http://www.coderanch.com/t/35096/Programming/Extract-lastname-lastname-firstname – Junior Mayhé Mar 12 '16 at 16:17
-
Doesn't this break with apostrophe? What about O'Brian for example. – sproketboy Sep 07 '16 at 11:11
-
1Note: to avoid resizing of the internally used `char[]` in `StringBuilder` I suggest using `new StringBuilder(input.length())` – Lino May 29 '19 at 09:49
-
3@sproketboy My idea was to provide an implementation for handling Java naming conventions, not for handling any kind of string representing names etc. Much more effort would be needed to properly handling all linguistic/regional differences for handling names. – dfa May 31 '19 at 08:45
-
Please note, this home-grown solution misses most of the title case rules. https://capitalizemytitle.com/ Words like "a", "an", and "the" are not supposed to be capitalized. The second part of a hyphenated word should be. Others have pointed out that proper names retain their capitalization, such as "O'Connor" But this solution will likely meet the needs of most people stopping here. So still a good answer. Reader beware. – Brent K. Feb 05 '20 at 19:28
If I may submit my take on the solution...
The following method is based on the one that dfa posted. It makes the following major change (which is suited to the solution I needed at the time): it forces all characters in the input string into lower case unless it is immediately preceded by an "actionable delimiter" in which case the character is coerced into upper case.
A major limitation of my routine is that it makes the assumption that "title case" is uniformly defined for all locales and is represented by the same case conventions I have used and so it is less useful than dfa's code in that respect.
public static String toDisplayCase(String s) {
final String ACTIONABLE_DELIMITERS = " '-/"; // these cause the character following
// to be capitalized
StringBuilder sb = new StringBuilder();
boolean capNext = true;
for (char c : s.toCharArray()) {
c = (capNext)
? Character.toUpperCase(c)
: Character.toLowerCase(c);
sb.append(c);
capNext = (ACTIONABLE_DELIMITERS.indexOf((int) c) >= 0); // explicit cast not needed
}
return sb.toString();
}
TEST VALUES
a string
maRTin o'maLLEY
john wilkes-booth
YET ANOTHER STRING
OUTPUTS
A String
Martin O'Malley
John Wilkes-Booth
Yet Another String
-
will not work with ligatures like lj, whose uppercase is LJ but titlecase is Lj. Use `Character.toTitleCase` instead. – mihi Feb 06 '14 at 19:14
-
@mihi: also will not work with other specialized rules, eg. surnames such as McNamara or MacDonald. – scottb Feb 13 '14 at 02:12
-
but these cases can inherently not be fixed. Using the correct case conversion function (titlecase is supposed to be used to capitalize a word, and not uppercase, according to Unicode rules) *can* be done (and it's easy). – mihi Feb 13 '14 at 18:36
-
-
It's true. This works well on name fields but, as you point out, not on general prose. It wouldn't even work well on all names, Vulcans in particular (T'Pau instead of T'pau). – scottb Sep 08 '14 at 16:41
Use WordUtils.capitalizeFully() from Apache Commons.
WordUtils.capitalizeFully(null) = null
WordUtils.capitalizeFully("") = ""
WordUtils.capitalizeFully("i am FINE") = "I Am Fine"

- 993
- 13
- 12
-
1Nice solution! Thanks! But this does not work 100 % of the time, as it also capitalizes e.g. "a" in this title: "This is a Title". See http://english.stackexchange.com/questions/14/which-words-in-a-title-should-be-capitalized. Do you know of any library that deals with this? – Eirik W Feb 02 '15 at 07:21
You can use apache commons langs like this :
WordUtils.capitalizeFully("this is a text to be capitalize")
you can find the java doc here : WordUtils.capitalizeFully java doc
and if you want to remove the spaces in between the worlds you can use :
StringUtils.remove(WordUtils.capitalizeFully("this is a text to be capitalize")," ")
you can find the java doc for String StringUtils.remove java doc
i hope this help.

- 121
- 1
- 6
If you want the correct answer according to the latest Unicode standard, you should use icu4j.
UCharacter.toTitleCase(Locale.US, "hello world", null, 0);
Note that this is locale sensitive.

- 509
- 4
- 7
-
Also see the newer ICU4J API CaseMap: http://icu-project.org/apiref/icu4j/com/ibm/icu/text/CaseMap.Title.html – sffc Nov 29 '18 at 23:19
-
Also available in Android API level 24: https://developer.android.com/reference/android/icu/lang/UCharacter.html – sffc Nov 29 '18 at 23:27
-
1I tested it with the following: "alexander and the terrible, horrible, no good, very bad day, by judith viorst and ray cruz" I expected: "Alexander and the Terrible, Horrible, No Good, Very Bad Day, by Judith Viorst and Ray Cruz" But the actual result was: "Alexander And The Terrible, Horrible, No Good, Very Bad Day, By Judith Viorst And Ray Cruz" Does not work as expected. It just uppercase every word in a phrase, same as other builtin solutions – chomp Jan 25 '21 at 14:06
-
@chomp You want an AI-based natural language processor. That's beyond the ability of most libraries mentioned here, and - I'd say - out of the scope of this question. "Title Case" means capitalising everything. – David Lavender Jul 14 '21 at 09:05
-
@DavidLavender I agree that could be hard to achieve, but one thing is "Title Case" and another one is "Fully Capitalized", perhaps the name could be misleading, or at least it was in my case. https://en.wikipedia.org/wiki/Title_case – chomp Jul 14 '21 at 12:24
Here's another take based on @dfa's and @scottb's answers that handles any non-letter/digit characters:
public final class TitleCase {
public static String toTitleCase(String input) {
StringBuilder titleCase = new StringBuilder(input.length());
boolean nextTitleCase = true;
for (char c : input.toLowerCase().toCharArray()) {
if (!Character.isLetterOrDigit(c)) {
nextTitleCase = true;
} else if (nextTitleCase) {
c = Character.toTitleCase(c);
nextTitleCase = false;
}
titleCase.append(c);
}
return titleCase.toString();
}
}
Given input:
MARY ÄNN O’CONNEŽ-ŠUSLIK
the output is
Mary Änn O’Connež-Šuslik
This is something I wrote to convert snake_case to lowerCamelCase but could easily be adjusted based on the requirements
private String convertToLowerCamel(String startingText)
{
String[] parts = startingText.split("_");
return parts[0].toLowerCase() + Arrays.stream(parts)
.skip(1)
.map(part -> part.substring(0, 1).toUpperCase() + part.substring(1).toLowerCase())
.collect(Collectors.joining());
}

- 141
- 1
- 1
- 4
-
Your answer works like a charm, however, the solution doesn't seem to handle single word sequence, maybe an if condition should suffice. – o12d10 Nov 07 '17 at 18:57
Use this method to convert a string to title case :
static String toTitleCase(String word) {
return Stream.of(word.split(" "))
.map(w -> w.toUpperCase().charAt(0) + w.toLowerCase().substring(1))
.reduce((s, s2) -> s + " " + s2)
.orElse("");
}

- 10,654
- 8
- 33
- 53

- 41
- 4
Using Spring's StringUtils
:
org.springframework.util.StringUtils.capitalize(someText);
If you're already using Spring anyway, this avoids bringing in another framework.

- 8,021
- 3
- 35
- 55
I know this is older one, but doesn't carry the simple answer, I needed this method for my coding so I added here, simple to use.
public static String toTitleCase(String input) {
input = input.toLowerCase();
char c = input.charAt(0);
String s = new String("" + c);
String f = s.toUpperCase();
return f + input.substring(1);
}

- 59,234
- 49
- 233
- 358

- 119
- 1
- 1
- 5
you can very well use
org.apache.commons.lang.WordUtils
or
CaseFormat
from Google's API.

- 471
- 6
- 17
-
1
-
CaseFormat only has formats typically used in program identifiers (UpperCamel, lower-hypen, UPPER_UNDERSCORE, etc.) and only supports ASCII text. It would not work well for converting to Title Case. – M. Justin Dec 13 '17 at 19:12
I had this problem and i searched for it then i made my own method using some java keywords just need to pass String variable as parameter and get output as proper titled String.
public class Main
{
public static void main (String[]args)
{
String st = "pARVeEN sISHOsIYA";
String mainn = getTitleCase (st);
System.out.println (mainn);
}
public static String getTitleCase(String input)
{
StringBuilder titleCase = new StringBuilder (input.length());
boolean hadSpace = false;
for (char c:input.toCharArray ()){
if(Character.isSpaceChar(c)){
hadSpace = true;
titleCase.append (c);
continue;
}
if(hadSpace){
hadSpace = false;
c = Character.toUpperCase(c);
titleCase.append (c);
}else{
c = Character.toLowerCase(c);
titleCase.append (c);
}
}
String temp=titleCase.toString ();
StringBuilder titleCase1 = new StringBuilder (temp.length ());
int num=1;
for (char c:temp.toCharArray ())
{ if(num==1)
c = Character.toUpperCase(c);
titleCase1.append (c);
num=0;
}
return titleCase1.toString ();
}
}

- 11
- 1
-
Here i did't use trim method anywhere beacause in my case i was getting proper trimmed string. – Parveen Sishodiya Oct 01 '19 at 17:17
It seems none of the answers format it in the actual title case: "How to Land Your Dream Job", "To Kill a Mockingbird", etc. so I've made my own method. Works best for English languages texts.
private final static Set<Character> TITLE_CASE_DELIMITERS = new HashSet<>();
static {
TITLE_CASE_DELIMITERS.add(' ');
TITLE_CASE_DELIMITERS.add('.');
TITLE_CASE_DELIMITERS.add(',');
TITLE_CASE_DELIMITERS.add(';');
TITLE_CASE_DELIMITERS.add('/');
TITLE_CASE_DELIMITERS.add('-');
TITLE_CASE_DELIMITERS.add('(');
TITLE_CASE_DELIMITERS.add(')');
}
private final static Set<String> TITLE_SMALLCASED_WORDS = new HashSet<>();
static {
TITLE_SMALLCASED_WORDS.add("a");
TITLE_SMALLCASED_WORDS.add("an");
TITLE_SMALLCASED_WORDS.add("the");
TITLE_SMALLCASED_WORDS.add("for");
TITLE_SMALLCASED_WORDS.add("in");
TITLE_SMALLCASED_WORDS.add("on");
TITLE_SMALLCASED_WORDS.add("of");
TITLE_SMALLCASED_WORDS.add("and");
TITLE_SMALLCASED_WORDS.add("but");
TITLE_SMALLCASED_WORDS.add("or");
TITLE_SMALLCASED_WORDS.add("nor");
TITLE_SMALLCASED_WORDS.add("to");
}
public static String toCapitalizedWord(String oneWord) {
if (oneWord.length() < 1) {
return oneWord.toUpperCase();
}
return "" + Character.toTitleCase(oneWord.charAt(0)) + oneWord.substring(1).toLowerCase();
}
public static String toTitledWord(String oneWord) {
if (TITLE_SMALLCASED_WORDS.contains(oneWord.toLowerCase())) {
return oneWord.toLowerCase();
}
return toCapitalizedWord(oneWord);
}
public static String toTitleCase(String str) {
StringBuilder result = new StringBuilder();
StringBuilder oneWord = new StringBuilder();
char previousDelimiter = 'x';
/* on start, always move to upper case */
for (char c : str.toCharArray()) {
if (TITLE_CASE_DELIMITERS.contains(c)) {
if (previousDelimiter == '-' || previousDelimiter == 'x') {
result.append(toCapitalizedWord(oneWord.toString()));
} else {
result.append(toTitledWord(oneWord.toString()));
}
oneWord.setLength(0);
result.append(c);
previousDelimiter = c;
} else {
oneWord.append(c);
}
}
if (previousDelimiter == '-' || previousDelimiter == 'x') {
result.append(toCapitalizedWord(oneWord.toString()));
} else {
result.append(toTitledWord(oneWord.toString()));
}
return result.toString();
}
public static void main(String[] args) {
System.out.println(toTitleCase("one year in paris"));
System.out.println(toTitleCase("How to Land Your Dream Job"));
}

- 3,071
- 2
- 29
- 44
This is the simplest solution
static void title(String a,String b){
String ra = Character.toString(Character.toUpperCase(a.charAt(0)));
String rb = Character.toString(Character.toUpperCase(b.charAt(0)));
for(int i=1;i<a.length();i++){
ra+=a.charAt(i);
}
for(int i=1;i<b.length();i++){
rb+=b.charAt(i);
}
System.out.println(ra+" "+rb);

- 29
- 6
I recently ran into this problem too and unfortunately had many occurences of names beginning with Mc and Mac, I ended up using a version of scottb's code which I changed to handle these prefixes so it's here in case anyone wants to use it.
There are still edge cases which this misses but the worst thing that can happen is that a letter will be lower case when it should be capitalized.
/**
* Get a nicely formatted representation of the name.
* Don't send this the whole name at once, instead send it the components.<br>
* For example: andrew macnamara would be returned as:<br>
* Andrew Macnamara if processed as a single string<br>
* Andrew MacNamara if processed as 2 strings.
* @param name
* @return correctly formatted name
*/
public static String getNameTitleCase (String name) {
final String ACTIONABLE_DELIMITERS = " '-/";
StringBuilder sb = new StringBuilder();
if (name !=null && !name.isEmpty()){
boolean capitaliseNext = true;
for (char c : name.toCharArray()) {
c = (capitaliseNext)?Character.toUpperCase(c):Character.toLowerCase(c);
sb.append(c);
capitaliseNext = (ACTIONABLE_DELIMITERS.indexOf((int) c) >= 0);
}
name = sb.toString();
if (name.startsWith("Mc") && name.length() > 2 ) {
char c = name.charAt(2);
if (ACTIONABLE_DELIMITERS.indexOf((int) c) < 0) {
sb = new StringBuilder();
sb.append (name.substring(0,2));
sb.append (name.substring(2,3).toUpperCase());
sb.append (name.substring(3));
name=sb.toString();
}
} else if (name.startsWith("Mac") && name.length() > 3) {
char c = name.charAt(3);
if (ACTIONABLE_DELIMITERS.indexOf((int) c) < 0) {
sb = new StringBuilder();
sb.append (name.substring(0,3));
sb.append (name.substring(3,4).toUpperCase());
sb.append (name.substring(4));
name=sb.toString();
}
}
}
return name;
}

- 995
- 9
- 19
Conversion to Proper Title Case :
String s= "ThiS iS SomE Text";
String[] arr = s.split(" ");
s = "";
for (String s1 : arr) {
s += WordUtils.capitalize(s1.toLowerCase()) + " ";
}
s = s.substring(0, s.length() - 1);
Result : "This Is Some Text"

- 29
- 3
This converter transform any string containing camel case, white-spaces, digits and other characters to sanitized title case.
/**
* Convert a string to title case in java (with tests).
*
* @author Sudipto Chandra
*/
public abstract class TitleCase {
/**
* Returns the character type. <br>
* <br>
* Digit = 2 <br>
* Lower case alphabet = 0 <br>
* Uppercase case alphabet = 1 <br>
* All else = -1.
*
* @param ch
* @return
*/
private static int getCharType(char ch) {
if (Character.isLowerCase(ch)) {
return 0;
} else if (Character.isUpperCase(ch)) {
return 1;
} else if (Character.isDigit(ch)) {
return 2;
}
return -1;
}
/**
* Converts any given string in camel or snake case to title case.
* <br>
* It uses the method getCharType and ignore any character that falls in
* negative character type category. It separates two alphabets of not-equal
* cases with a space. It accepts numbers and append it to the currently
* running group, and puts a space at the end.
* <br>
* If the result is empty after the operations, original string is returned.
*
* @param text the text to be converted.
* @return a title cased string
*/
public static String titleCase(String text) {
if (text == null || text.length() == 0) {
return text;
}
char[] str = text.toCharArray();
StringBuilder sb = new StringBuilder();
boolean capRepeated = false;
for (int i = 0, prev = -1, next; i < str.length; ++i, prev = next) {
next = getCharType(str[i]);
// trace consecutive capital cases
if (prev == 1 && next == 1) {
capRepeated = true;
} else if (next != 0) {
capRepeated = false;
}
// next is ignorable
if (next == -1) {
// System.out.printf("case 0, %d %d %s\n", prev, next, sb.toString());
continue; // does not append anything
}
// prev and next are of same type
if (prev == next) {
sb.append(str[i]);
// System.out.printf("case 1, %d %d %s\n", prev, next, sb.toString());
continue;
}
// next is not an alphabet
if (next == 2) {
sb.append(str[i]);
// System.out.printf("case 2, %d %d %s\n", prev, next, sb.toString());
continue;
}
// next is an alphabet, prev was not +
// next is uppercase and prev was lowercase
if (prev == -1 || prev == 2 || prev == 0) {
if (sb.length() != 0) {
sb.append(' ');
}
sb.append(Character.toUpperCase(str[i]));
// System.out.printf("case 3, %d %d %s\n", prev, next, sb.toString());
continue;
}
// next is lowercase and prev was uppercase
if (prev == 1) {
if (capRepeated) {
sb.insert(sb.length() - 1, ' ');
capRepeated = false;
}
sb.append(str[i]);
// System.out.printf("case 4, %d %d %s\n", prev, next, sb.toString());
}
}
String output = sb.toString().trim();
output = (output.length() == 0) ? text : output;
//return output;
// Capitalize all words (Optional)
String[] result = output.split(" ");
for (int i = 0; i < result.length; ++i) {
result[i] = result[i].charAt(0) + result[i].substring(1).toLowerCase();
}
output = String.join(" ", result);
return output;
}
/**
* Test method for the titleCase() function.
*/
public static void testTitleCase() {
System.out.println("--------------- Title Case Tests --------------------");
String[][] samples = {
{null, null},
{"", ""},
{"a", "A"},
{"aa", "Aa"},
{"aaa", "Aaa"},
{"aC", "A C"},
{"AC", "Ac"},
{"aCa", "A Ca"},
{"ACa", "A Ca"},
{"aCamel", "A Camel"},
{"anCamel", "An Camel"},
{"CamelCase", "Camel Case"},
{"camelCase", "Camel Case"},
{"snake_case", "Snake Case"},
{"toCamelCaseString", "To Camel Case String"},
{"toCAMELCase", "To Camel Case"},
{"_under_the_scoreCamelWith_", "Under The Score Camel With"},
{"ABDTest", "Abd Test"},
{"title123Case", "Title123 Case"},
{"expect11", "Expect11"},
{"all0verMe3", "All0 Ver Me3"},
{"___", "___"},
{"__a__", "A"},
{"_A_b_c____aa", "A B C Aa"},
{"_get$It132done", "Get It132 Done"},
{"_122_", "122"},
{"_no112", "No112"},
{"Case-13title", "Case13 Title"},
{"-no-allow-", "No Allow"},
{"_paren-_-allow--not!", "Paren Allow Not"},
{"Other.Allow.--False?", "Other Allow False"},
{"$39$ldl%LK3$lk_389$klnsl-32489 3 42034 ", "39 Ldl Lk3 Lk389 Klnsl32489342034"},
{"tHis will BE MY EXAMple", "T His Will Be My Exa Mple"},
{"stripEvery.damn-paren- -_now", "Strip Every Damn Paren Now"},
{"getMe", "Get Me"},
{"whatSthePoint", "What Sthe Point"},
{"n0pe_aLoud", "N0 Pe A Loud"},
{"canHave SpacesThere", "Can Have Spaces There"},
{" why_underScore exists ", "Why Under Score Exists"},
{"small-to-be-seen", "Small To Be Seen"},
{"toCAMELCase", "To Camel Case"},
{"_under_the_scoreCamelWith_", "Under The Score Camel With"},
{"last one onTheList", "Last One On The List"}
};
int pass = 0;
for (String[] inp : samples) {
String out = titleCase(inp[0]);
//String out = WordUtils.capitalizeFully(inp[0]);
System.out.printf("TEST '%s'\nWANTS '%s'\nFOUND '%s'\n", inp[0], inp[1], out);
boolean passed = (out == null ? inp[1] == null : out.equals(inp[1]));
pass += passed ? 1 : 0;
System.out.println(passed ? "-- PASS --" : "!! FAIL !!");
System.out.println();
}
System.out.printf("\n%d Passed, %d Failed.\n", pass, samples.length - pass);
}
public static void main(String[] args) {
// run tests
testTitleCase();
}
}
Here are some inputs:
aCamel
TitleCase
snake_case
fromCamelCASEString
ABCTest
expect11
_paren-_-allow--not!
why_underScore exists
last one onTheList
And my outputs:
A Camel
Title Case
Snake Case
From Camel Case String
Abc Test
Expect11
Paren Allow Not
Why Under Score Exists
Last One On The List

- 6,999
- 4
- 31
- 48
Without dependency -
public static String capitalizeFirstLetter(String s) {
if(s.trim().length()>0){
return s.substring(0, 1).toUpperCase() + s.substring(1);
}
return s;
}
public static String createTitleCase(String s) {
if(s.trim().length()>0){
final StringBuilder sb = new StringBuilder();
String[] strArr = s.split("\\s");
for(int t =0; t < strArr.length; t++) {
sb.append(capitalizeFirstLetter(strArr[t]));
if(t != strArr.length-1) {
sb.append(" ");
}
}
s = sb.toString();
sb.setLength(0);
}
return s;
}

- 53
- 1
- 7
-
This throws away all spacing, turning it into UpperCamelCase, not Title Case. – M. Justin Jan 04 '23 at 04:56
-
-
Your latest updated version fixes the UpperCamelCase issue. It works so long as you're OK normalizing all spaces to a single space. If the exact spacing needs to be preserved (e.g. `" "` should remain `" "` and not become `" "`, or `"\n"` should remain a newline instead of being converted to a space), then this solution couldn't be used as-is without modification. – M. Justin Jul 11 '23 at 17:49
-
Yep it is too very long to reply, Validation should be done before passing values it is upto developer's work. Empty space is also a string, We cannot bound/restrict application/usage. That's why inbuilt methods are working for its need. Hence if you want to do your stuff there, you can :) – Thangaraj Jul 12 '23 at 14:21
-
Sorry, I misread and thought this was splitting on runs of spaces (e.g. `\\s+`), not single spaces `\\s`. Though it does still normalize spacing, which may or may not be desired (e.g. `abc\tde\tf` -> `Abc De F` instead of `Abc\tDe\tF`. – M. Justin Jul 12 '23 at 16:18
This should work:
String str="i like pancakes";
String arr[]=str.split(" ");
String strNew="";
for(String str1:arr)
{
Character oldchar=str1.charAt(0);
Character newchar=Character.toUpperCase(str1.charAt(0));
strNew=strNew+str1.replace(oldchar,newchar)+" ";
}
System.out.println(strNew);

- 1,748
- 6
- 18
- 24

- 1
-
1This is not a valid answer as the OP asked for *builtin* function. See also the comment which addresses the hidden complexity behind this, i.e. i18n. – Marcus May 29 '19 at 11:10
The simplest way of converting any string into a title case, is to use googles package org.apache.commons.lang.WordUtils
System.out.println(WordUtils.capitalizeFully("tHis will BE MY EXAMple"));
Will result this
This Will Be My Example
I'm not sure why its named "capitalizeFully", where in fact the function is not doing a full capital result, but anyways, thats the tool that we need.

- 182
- 1
- 3
-
1It is named `capitalizeFully` because it capitalizes every word, including those that should be lower case in a title. http://grammar.about.com/od/tz/g/Title-Case.htm – aij Jan 12 '16 at 19:44
-
2Apache Commons is not owned by Google. It's maintained by the Apache Software Foundation. http://commons.apache.org/ – ATutorMe Feb 09 '17 at 09:37
Sorry I am a beginner so my coding habit sucks!
public class TitleCase {
String title(String sent)
{
sent =sent.trim();
sent = sent.toLowerCase();
String[] str1=new String[sent.length()];
for(int k=0;k<=str1.length-1;k++){
str1[k]=sent.charAt(k)+"";
}
for(int i=0;i<=sent.length()-1;i++){
if(i==0){
String s= sent.charAt(i)+"";
str1[i]=s.toUpperCase();
}
if(str1[i].equals(" ")){
String s= sent.charAt(i+1)+"";
str1[i+1]=s.toUpperCase();
}
System.out.print(str1[i]);
}
return "";
}
public static void main(String[] args) {
TitleCase a = new TitleCase();
System.out.println(a.title(" enter your Statement!"));
}
}

- 3,273
- 2
- 36
- 54