Java - How To Capitalize The First Character of Each Word in A String - Stack Overflow
Java - How To Capitalize The First Character of Each Word in A String - Stack Overflow
Is there a function built into Java that capitalizes the first character of each word in a String, and does not affect the others?
Examples:
miles o'Brien -> Miles O'Brien (B remains capital, this rules out Title Case)
old mcdonald -> Old Mcdonald *
*( Old McDonald would be find too, but I don't expect it to be THAT smart.)
A quick look at the Java String Documentation reveals only toUpperCase() and toLowerCase() , which of course do not provide the desired
behavior. Naturally, Google results are dominated by those two functions. It seems like a wheel that must have been invented already, so it
couldn't hurt to ask so I can use it in the future.
12 What about old mcdonald ? Should that become Old McDonald ? Bart Kiers Dec 12 '09 at 13:34
2 I don't expect the function to be that smart. (Although if you have one I'd be happy to see it.) Just Up the
first letter after white space, but ignore the rest. WillfulWizard Dec 12 '09 at 18:56
1 You wouldn't be able to find an algorithm that properly handles name capitalization after the fact anyway ...
as long as there are pairs of names, either of which may be correct for a given person, like MacDonald and
Macdonald, the function would have no way of knowing which was correct. It's better to do what you did,
although you'll still get some names wrong (like von Neumann). Dave DuPlantis Jun 10 '11 at 19:49
36 Answers
1 2 next
(Note: if you need "fOO BAr" to become "Foo Bar" , then use capitalizeFully(..)
instead)
4 I think you mean WordUtils.capitalize(str). See API for details. Hans Doggen Dec 12 '09 at 8:33
63 Keeping my philosophy of always voting up answers that refer to the commons libraries. Ravi Wallau
Dec 12 '09 at 8:59
8 To change the non-first letter to the words to lowercase, use capitalizeFully(str). Umesh Rajbhandari Feb
13 '12 at 5:23
2 @BasZero it is the right answer to the question asked. I will include the Fully version as a comment.
Bozho Mar 14 '13 at 16:36
https://stackoverflow.com/questions/1892765/how-to-capitalize-the-first-character-of-each-word-in-a-string 1/12
9/24/2017 java - How to capitalize the first character of each word in a string - Stack Overflow
If you're only worried about the first letter of the first word being capitalized:
2 this only changes the first letter of the first word Chrizzz Apr 9 '14 at 8:36
9 @nbolton - But it explicitly ignores the intent of the question, and fails for the very cases given in that
example - and it adds little or nothing to the answers previously given! David Manheim Dec 28 '14 at 4:38
14 This piece of code is not crash-safe! Imagine line being null or having a length of < 2. stk Apr 20 '15 at
12:15
The following method converts all the letters into upper/lower case, depending on their position
near a space or other special chars.
3 Doesn't work for surrogate pairs... Tom Hawtin - tackline Dec 12 '09 at 13:01
@bancer, with your example you can't control which characters won't be followed by an uppercase letter.
True Soft Nov 9 '12 at 20:34
@TrueSoft, I do not understand you. Why do you need to control what characters follows after uppercase
letter? As I understood it is important that the preceding character would not be a letter and my example
ensures that. Just replace your if-else-if block with my if-else block and run a test. bancer Nov 10 '12 at
1:09
6 I like having answers that don't use the commons library, because every once in a while you can't use it.
Heckman Jul 18 '13 at 16:52
https://stackoverflow.com/questions/1892765/how-to-capitalize-the-first-character-of-each-word-in-a-string 2/12
9/24/2017 java - How to capitalize the first character of each word in a string - Stack Overflow
2,773 1 13 28 339 1 4 10
23 @Chrizzz so do not commit code you did not test... If you provide an empty string, it does crash. Your fault,
not Neelam's. Reinherd May 19 '14 at 10:26
If there is a space at the end then it is crashing then I added trim() first and split string with space.It worked
perfectly Hanuman Dec 14 '16 at 16:29
Optional multiple delimiters , each one with its behavior (capitalize before, after, or both, to
handle cases like O'Brian );
Optional Locale ;
LIVE DEMO
Output:
====================================
SIMPLE USAGE
====================================
Source: cApItAlIzE this string after WHITE SPACES
Output: Capitalize This String After White Spaces
====================================
SINGLE CUSTOM-DELIMITER USAGE
====================================
Source: capitalize this string ONLY before'and''after'''APEX
Output: Capitalize this string only beforE'AnD''AfteR'''Apex
====================================
MULTIPLE CUSTOM-DELIMITER USAGE
====================================
Source: capitalize this string AFTER SPACES, BEFORE'APEX, and #AFTER AND BEFORE# NUMBER
SIGN (#)
Output: Capitalize This String After Spaces, BeforE'apex, And #After And BeforE# Number
Sign (#)
====================================
SIMPLE USAGE WITH CUSTOM LOCALE
====================================
Source: Uniforming the first and last vowels (different kind of 'i's) of the Turkish word
D[]YARBAK[I]R (DYARBAKIR)
Output: Uniforming The First And Last Vowels (different Kind Of 'i's) Of The Turkish Word
D[i]yarbak[i]r (diyarbakir)
====================================
SIMPLE USAGE WITH A SURROGATE PAIR
====================================
Source: ab c de
Output: Ab c De
Note: first letter will always be capitalized (edit the source if you don't want that).
Please share your comments and help me to found bugs or to improve the code...
Code:
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
https://stackoverflow.com/questions/1892765/how-to-capitalize-the-first-character-of-each-word-in-a-string 3/12
9/24/2017 java - How to capitalize the first character of each word in a string - Stack Overflow
chars[0] = Character.toUpperCase(chars[0]);
}
https://stackoverflow.com/questions/1892765/how-to-capitalize-the-first-character-of-each-word-in-a-string 4/12
9/24/2017 java - How to capitalize the first character of each word in a string - Stack Overflow
1,206 3 25 53
1 Hmmm, I think the second line in the for loop should read: toBeCapped += " " + capLetter +
tokens[i].substring(1, tokens[i].length()); jengelsma Mar 30 '12 at 23:50
1 But this solution will add a whitespace at the starting. So you may need to do left trim. Kamalakannan J
Jul 22 '15 at 10:49
capitalizeStr = StringUtils.capitalize(str);
Use the Split method to split your string into words, then use the built in string functions to
capitalize each word, then append together.
Pseudo-code (ish)
string += word
In the end string looks something like "The Sentence You Want To Apply Caps To"
This might be useful if you need to capitalize titles. It capitalizes each substring delimited by "
" , except for specified strings such as "a" or "the" . I haven't ran it yet because it's late,
should be fine though. Uses Apache Commons StringUtils.join() at one point. You can
substitute it with a simple loop if you wish.
https://stackoverflow.com/questions/1892765/how-to-capitalize-the-first-character-of-each-word-in-a-string 5/12
9/24/2017 java - How to capitalize the first character of each word in a string - Stack Overflow
for(String w : words){
result += (w.length() > 1? w.substring(0, 1).toUpperCase(Locale.US) +
w.substring(1, w.length()).toLowerCase(Locale.US) : w) + " ";
}
return result.trim();
}
1 Always use StringBuilder when you concatenate rather than += chitgoks Apr 23 at 1:44
try
{
String str = br.readLine();
char[] str1 = new char[str.length()];
str1[0] = Character.toUpperCase(str1[0]);
for(int i=0;i<str.length();i++)
{
if(str1[i] == ' ')
{
str1[i+1] = Character.toUpperCase(str1[i+1]);
}
System.out.print(str1[i]);
}
}
catch(Exception e)
{
System.err.println("Error: " + e.getMessage());
}
This is the most simple, basic and best answer for a novice like me! abhishah901 Oct 29 '15 at 15:41
String example="hello";
example=example.substring(0,1).toUpperCase()+example.substring(1, example.length());
System.out.println(example);
Result: Hello
4 what about HELLO it returns HELLO but expected Hello so you shall use toLowerCase() in second
SubString Trikaldarshi Sep 21 '13 at 18:33
There are many how to convert the first letter of the first word being capitalized. I have an idea.
It's very simple:
l += s.charAt(i);
https://stackoverflow.com/questions/1892765/how-to-capitalize-the-first-character-of-each-word-in-a-string 6/12
9/24/2017 java - How to capitalize the first character of each word in a string - Stack Overflow
Code is whitespace) */
l += s.toUpperCase().charAt(i+1); /*uppercase the letter after whitespace
*/
i++; /*to i = i + 1 because we don't need to
add
value whitespace into string l */
}
}
return l;
}
Thanks for trying to add an answer. This is a reasonable idea, but note that there are basic functions that do
this already, and code that does this similarly to what you provided, and the accepted answers already
outline all of them very clearly. David Manheim Dec 28 '14 at 4:39
package com.test;
/**
* @author Prasanth Pillai
* @date 01-Feb-2012
* @description : Below is the test class details
*
* inputs a String from a user. Expect the String to contain spaces and alphanumeric
characters only.
* capitalizes all first letters of the words in the given String.
* preserves all other characters (including spaces) in the String.
* displays the result to the user.
*
* Approach : I have followed a simple approach. However there are many string
utilities available
* for the same purpose. Example : WordUtils.capitalize(str) (from apache commons-lang)
*
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
https://stackoverflow.com/questions/1892765/how-to-capitalize-the-first-character-of-each-word-in-a-string 7/12
9/24/2017 java - How to capitalize the first character of each word in a string - Stack Overflow
return result.trim();
}
1 Don't use string-concation for creating long strings, it's painfully slow:
stackoverflow.com/questions/15177987/ Lukas Knuth Mar 21 '13 at 12:20
I'm not sure how to use this SO answer box yet, but here is my solution. I ran across this
problem tonight and decided to search it. I found an answer by Neelam Singh that was almost
there so I decided to fix the issue (broke on empty strings) and causes system crash.
The method you are looking for is named capString(String s) below. It turns "It's only 5am
here" into "It's Only 5am Here".
https://stackoverflow.com/questions/1892765/how-to-capitalize-the-first-character-of-each-word-in-a-string 8/12
9/24/2017 java - How to capitalize the first character of each word in a string - Stack Overflow
The code is pretty well commented, so enjoy. Cheers!
package com.lincolnwdaniel.interactivestory.model;
/**
* @param s is a string of any length, ideally only one word
* @return a capitalized string.
* only the first letter of the string is made to uppercase
*/
public static String capSingleWord(String s) {
if(s.isEmpty() || s.length()<2) {
return Character.toUpperCase(s.charAt(0))+"";
} else {
return Character.toUpperCase(s.charAt(0)) + s.substring(1);
}
}
/**
*
* @param s is a string of any length
* @return a title cased string.
* All first letter of each word is made to uppercase
*/
public static String capString(String s) {
//check if the string is empty, if it is, return it immediately
if(s.isEmpty()){
return s;
}
//check if the array is empty (would be caused by the passage of s as an empty string
[i.g "" or " "],
//if it is, return the original string immediately
if( arr.length < 1 ){
return s;
}
Function:
https://stackoverflow.com/questions/1892765/how-to-capitalize-the-first-character-of-each-word-in-a-string 9/12
9/24/2017 java - How to capitalize the first character of each word in a string - Stack Overflow
return sb.toString();
}
Example call:
Result:
Close, but not exactly. I don't want the letters after the first to be changed. Title case enforces that the other
letters are set to Lower. WillfulWizard Dec 12 '09 at 18:58
For those of you using Velocity in your MVC, you can use the capitalizeFirstLetter() method
from the StringUtils class.
name = (name.length() != 0) ?
name.toString().toLowerCase().substring(0,1).toUpperCase().concat(name.substring(1)):
name;
--------------------
Output
--------------------
Test
T
empty
--------------------
without error if you try and change the name value to the three of values .Error free
this one work for Surname case.. with different type of separator, and keep the same sepator
jean-frederic --> Jean-Frederic jean frederic --> Jean Frederic
https://stackoverflow.com/questions/1892765/how-to-capitalize-the-first-character-of-each-word-in-a-string 10/12
9/24/2017 java - How to capitalize the first character of each word in a string - Stack Overflow
public static String capitalize (String givenString) {
String Separateur = " ,.-;";
StringBuffer sb = new StringBuffer();
boolean ToCap = true;
for (int i = 0; i < givenString.length(); i++) {
if (ToCap)
sb.append(Character.toUpperCase(givenString.charAt(i)));
else
sb.append(Character.toLowerCase(givenString.charAt(i)));
if (Separateur.indexOf(givenString.charAt(i)) >=0)
ToCap = true;
else
ToCap = false;
}
return sb.toString().trim();
}
package corejava.string.intern;
import java.io.DataInputStream;
import java.util.ArrayList;
/*
* wap to accept only 3 sentences and convert first character of each word into upper case
*/
/**
* @param args
*/
public static void main(String[] args) throws java.lang.Exception{
/*
* this will display all the elements in an array
*/
public static void display(){
for(String display:list){
System.out.println(display);
}
}
/*
* this divide the line of string into words
* and first char of the each word is converted to upper case
* and to an array list
*/
public static void method(String lineParam){
words=line.split("\\s");
for(String s:words){
String result=s.substring(0,1).toUpperCase()+s.substring(1);
list.add(result);
}
}
https://stackoverflow.com/questions/1892765/how-to-capitalize-the-first-character-of-each-word-in-a-string 11/12
9/24/2017 java - How to capitalize the first character of each word in a string - Stack Overflow
try this
I had a requirement to make a generic toString(Object obj) helper class function, where I had
to convert the fieldnames into methodnames - getXXX() of the passed Object.
/**
* @author DPARASOU
* Utility method to replace the first char of a string with uppercase but leave other
chars as it is.
* ToString()
* @param inStr - String
* @return String
*/
public static String firstCaps(String inStr)
{
if (inStr != null && inStr.length() > 0)
{
char[] outStr = inStr.toCharArray();
outStr[0] = Character.toUpperCase(outStr[0]);
return String.valueOf(outStr);
}
else
return inStr;
}
1 2 next
https://stackoverflow.com/questions/1892765/how-to-capitalize-the-first-character-of-each-word-in-a-string 12/12