Вы находитесь на странице: 1из 12

9/24/2017 java - How to capitalize the first character of each word in a string - Stack Overflow

Learn, Share, Build


Each month, over 50 million developers come to Stack Overflow to Google Facebook
learn, share their knowledge, and build their careers. OR

Join the worlds largest developer community.

How to capitalize the first character of each word in a string

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:

jon skeet -> Jon Skeet

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.

java string capitalization

edited May 7 '16 at 1:15 asked Dec 12 '09 at 8:25


the Tin Man WillfulWizard
123k 25 154 224 2,181 2 13 15

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

releated: stackoverflow.com/questions/1149855/ Chris Nov 6 '10 at 11:19

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

WordUtils.capitalize(str) (from apache commons-lang)

(Note: if you need "fOO BAr" to become "Foo Bar" , then use capitalizeFully(..)
instead)

edited May 8 '16 at 8:15 answered Dec 12 '09 at 8:30


Andrew Tobilko Bozho
11.9k 5 22 59 431k 94 858 1006

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

3 Yup, code reuse is a sensible policy :) Bozho Dec 12 '09 at 9:00

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:

private String capitalize(final String line) {


return Character.toUpperCase(line.charAt(0)) + line.substring(1);
}

edited Mar 14 '15 at 21:15 answered Jun 22 '12 at 2:48


Jared Burrows Nick Bolton
32.1k 16 105 136 15.2k 49 140 214

2 this only changes the first letter of the first word Chrizzz Apr 9 '14 at 8:36

22 Indeed, this was my intention. Nick Bolton Apr 10 '14 at 8:51

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

1 Solution doesnt solve the question! abhishah901 Oct 29 '15 at 15:29

The following method converts all the letters into upper/lower case, depending on their position
near a space or other special chars.

public static String capitalizeString(String string) {


char[] chars = string.toLowerCase().toCharArray();
boolean found = false;
for (int i = 0; i < chars.length; i++) {
if (!found && Character.isLetter(chars[i])) {
chars[i] = Character.toUpperCase(chars[i]);
found = true;
} else if (Character.isWhitespace(chars[i]) || chars[i]=='.' || chars[i]=='\'') { //
You can add other chars here
found = false;
}
}
return String.valueOf(chars);
}

answered Dec 12 '09 at 8:53


True Soft
6,919 6 36 70

3 Doesn't work for surrogate pairs... Tom Hawtin - tackline Dec 12 '09 at 13:01

I would improve and simplify the loop conditions: if(Character.isLetter(chars[i])) { if(!found) {


chars[i] = Character.toUpperCase(chars[i]); } found = true; } else { found = false; } .
bancer Nov 9 '12 at 1:19

@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

Try this very simple way

example givenString="ram is good boy"

public static String toTitleCase(String givenString) {


String[] arr = givenString.split(" ");
StringBuffer sb = new StringBuffer();

for (int i = 0; i < arr.length; i++) {


sb.append(Character.toUpperCase(arr[i].charAt(0)))
.append(arr[i].substring(1)).append(" ");
}
return sb.toString().trim();
}

Output will be: Ram Is Good Boy

edited Aug 13 '14 at 10:31 answered Feb 13 '13 at 7:56


vilpe89 Neelam Singh

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

1 this code caused our server to crash:java.lang.StringIndexOutOfBoundsException: String index out of


range: 0 Chrizzz Apr 9 '14 at 12:38

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

I've written a small Class to capitalize all the words in a String.

Optional multiple delimiters , each one with its behavior (capitalize before, after, or both, to
handle cases like O'Brian );

Optional Locale ;

Don't breaks with Surrogate Pairs .

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;

public class WordsCapitalizer {

public static String capitalizeEveryWord(String source) {


return capitalizeEveryWord(source,null,null);
}

public static String capitalizeEveryWord(String source, Locale locale) {


return capitalizeEveryWord(source,null,locale);
}

public static String capitalizeEveryWord(String source, List<Delimiter> delimiters,


Locale locale) {
char[] chars;

if (delimiters == null || delimiters.size() == 0)


delimiters = getDefaultDelimiters();

// If Locale specified, i18n toLowerCase is executed, to handle specific behaviors


(eg. Turkish dotted and dotless 'i')
if (locale!=null)
chars = source.toLowerCase(locale).toCharArray();
else
chars = source.toLowerCase().toCharArray();

// First charachter ALWAYS capitalized, if it is a Letter.


if (chars.length>0 && Character.isLetter(chars[0]) && !isSurrogate(chars[0])){

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]);
}

for (int i = 0; i < chars.length; i++) {


if (!isSurrogate(chars[i]) && !Character.isLetter(chars[i])) {
// Current char is not a Letter; gonna check if it is a delimitrer.
for (Delimiter delimiter : delimiters){
if (delimiter.getDelimiter()==chars[i]){
// Delimiter found, applying rules...
if (delimiter.capitalizeBefore() && i>0
&& Character.isLetter(chars[i-1]) && !isSurrogate(chars[i-1]))
{ // previous character is a Letter and I have to capitalize it
chars[i-1] = Character.toUpperCase(chars[i-1]);
}
if (delimiter.capitalizeAfter() && i<chars.length-1
&& Character.isLetter(chars[i+1]) && !isSurrogate(chars[i+1]))
{ // next character is a Letter and I have to capitalize it
chars[i+1] = Character.toUpperCase(chars[i+1]);
}
break;
}
}
}
}
return String.valueOf(chars);
}

private static boolean isSurrogate(char chr){


// Check if the current character is part of an UTF-16 Surrogate Pair.
// Note: not validating the pair, just used to bypass (any found part of) it.
return (Character.isHighSurrogate(chr) || Character.isLowSurrogate(chr));
}

private static List<Delimiter> getDefaultDelimiters(){


// If no delimiter specified, "Capitalize after space" rule is set by default.
List<Delimiter> delimiters = new ArrayList<Delimiter>();
delimiters.add(new Delimiter(Behavior.CAPITALIZE_AFTER_MARKER, ' '));
return delimiters;
}

public static class Delimiter {


private Behavior behavior;
private char delimiter;

public Delimiter(Behavior behavior, char delimiter) {


super();
this.behavior = behavior;
this.delimiter = delimiter;
}

public boolean capitalizeBefore(){


return (behavior.equals(Behavior.CAPITALIZE_BEFORE_MARKER)
|| behavior.equals(Behavior.CAPITALIZE_BEFORE_AND_AFTER_MARKER));
}

public boolean capitalizeAfter(){


return (behavior.equals(Behavior.CAPITALIZE_AFTER_MARKER)
|| behavior.equals(Behavior.CAPITALIZE_BEFORE_AND_AFTER_MARKER));
}

public char getDelimiter() {


return delimiter;
}
}

public static enum Behavior {


CAPITALIZE_AFTER_MARKER(0),
CAPITALIZE_BEFORE_MARKER(1),
CAPITALIZE_BEFORE_AND_AFTER_MARKER(2);

private int value;

private Behavior(int value) {


this.value = value;
}

public int getValue() {


return value;
}
}

edited Nov 30 '12 at 17:28 answered Nov 30 '12 at 16:55


Andrea Ligios
36k 11 68 114

String toBeCapped = "i want this sentence capitalized";

String[] tokens = toBeCapped.split("\\s");


toBeCapped = "";

for(int i = 0; i < tokens.length; i++){


char capLetter = Character.toUpperCase(tokens[i].charAt(0));
toBeCapped += " " + capLetter + tokens[i].substring(1);
}
toBeCapped = toBeCapped.trim();

edited Jul 22 '15 at 15:06 answered Aug 10 '11 at 14:10


Reid Mac

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

Using org.apache.commons.lang.StringUtils make it very simple.

capitalizeStr = StringUtils.capitalize(str);

edited May 8 '16 at 8:17 answered Jun 11 '15 at 10:48


Andrew Tobilko Amir Bareket
11.9k 5 22 59 283 3 8

@Ash StringUtils.capitalise(str) is deprecated. See: commons.apache.org/proper/commons-


lang/javadocs/api-2.6/org/ Navigatron Feb 20 at 12:11

WordUtils shows as deprecated. This is not. Wesos de Queso Jul 17 at 1:59

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 = "the sentence you want to apply caps to";


words = string.split(" ")
string = ""
for(String w: words)

//This line is an easy way to capitalize a word


word = word.toUpperCase().replace(word.substring(1), word.substring(1).toLowerCase())

string += word

In the end string looks something like "The Sentence You Want To Apply Caps To"

answered Jul 24 '12 at 23:59


Paul
41 1

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.

private static String capitalize(String string) {


if (string == null) return null;
String[] wordArray = string.split(" "); // Split string to analyze word by word.
int i = 0;
lowercase:
for (String word : wordArray) {
if (word != wordArray[0]) { // First word always in capital
String [] lowercaseWords = {"a", "an", "as", "and", "although", "at",
"because", "but", "by", "for", "in", "nor", "of", "on", "or", "so", "the", "to", "up",
"yet"};
for (String word2 : lowercaseWords) {
if (word.equals(word2)) {
wordArray[i] = word;
i++;
continue lowercase;
}
}
}
char[] characterArray = word.toCharArray();
characterArray[0] = Character.toTitleCase(characterArray[0]);
wordArray[i] = new String(characterArray);
i++;
}
return StringUtils.join(wordArray, " "); // Re-join string
}

edited Oct 3 '12 at 13:39 answered Oct 2 '12 at 19:45


Dominykas Mostauskis
3,183 1 22 38

im using this function i think is faster in performance.

public static String capitalize(String text){


String c = (text != null)? text.trim() : "";
String[] words = c.split(" ");
String result = "";

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();
}

answered Oct 7 '16 at 20:55


Tassadar
196 1 5

1 Always use StringBuilder when you concatenate rather than += chitgoks Apr 23 at 1:44

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter the sentence : ");

try
{
String str = br.readLine();
char[] str1 = new char[str.length()];

for(int i=0; i<str.length(); i++)


{
str1[i] = Character.toLowerCase(str.charAt(i));
}

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());
}

edited Aug 8 '11 at 13:04 answered Aug 8 '11 at 8:03


Jason Plank Suganya
2,131 4 24 38 31 1

This is the most simple, basic and best answer for a novice like me! abhishah901 Oct 29 '15 at 15:41

With this simple code:

String example="hello";

example=example.substring(0,1).toUpperCase()+example.substring(1, example.length());

System.out.println(example);

Result: Hello

answered May 25 '13 at 21:58


Adrian
167 1 6

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:

public String capitalize(String str){

/* The first thing we do is remove whitespace from string*/


String c = str.replaceAll("\\s+", " ");
String s = c.trim();
String l = "";

for(int i = 0; i < s.length(); i++){


if(i == 0){ /*uppercase the first letter in
strings*/
l += s.toUpperCase().charAt(i);
i++; /*to i = i + 1 because we don't need to
add
value i = 0 into string l */
}

l += s.charAt(i);

if(s.charAt(i) == 32){ /*if we meet whitespace (32 in ASCII

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;
}

answered Dec 28 '14 at 4:22


Phuoc Le
31 1

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;

public class Test {

public static void main(String[] args) throws IOException{


System.out.println("Input String :\n");
InputStreamReader converter = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(converter);
String inputString = in.readLine();
int length = inputString.length();
StringBuffer newStr = new StringBuffer(0);
int i = 0;
int k = 0;
/* This is a simple approach
* step 1: scan through the input string
* step 2: capitalize the first letter of each word in string
* The integer k, is used as a value to determine whether the
* letter is the first letter in each word in the string.
*/

while( i < length){


if (Character.isLetter(inputString.charAt(i))){
if ( k == 0){
newStr = newStr.append(Character.toUpperCase(inputString.charAt(i)));
k = 2;
}//this else loop is to avoid repeatation of the first letter in output string
else {
newStr = newStr.append(inputString.charAt(i));
}
} // for the letters which are not first letter, simply append to the output
string.
else {
newStr = newStr.append(inputString.charAt(i));
k=0;
}
i+=1;
}
System.out.println("new String ->"+newStr);
}
}

answered Feb 1 '12 at 12:30


Prasanth
21 1

Here is a simple function

public static String capEachWord(String source){


String result = "";
String[] splitString = source.split(" ");
for(String target : splitString){
result += Character.toUpperCase(target.charAt(0))
+ target.substring(1) + " ";
}

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();
}

edited Mar 21 '13 at 12:18 answered Mar 20 '13 at 12:59


Lukas Knuth Himanshu Agrawal
19.5k 12 60 91 31 1

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

If I'm not too late to the party here's my answer:

String text = "jon skeet, miles o'brien, old mcdonald";

Pattern pattern = Pattern.compile("\\b([a-z])([\\w]*)");


Matcher matcher = pattern.matcher(text);
StringBuffer buffer = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(buffer, matcher.group(1).toUpperCase() +
matcher.group(2));
}
String capitalized = matcher.appendTail(buffer).toString();
System.out.println(capitalized);

answered Nov 26 '13 at 22:23


curd0
1,150 2 14 22

This is just another way of doing it:

private String capitalize(String line)


{
StringTokenizer token =new StringTokenizer(line);
String CapLine="";
while(token.hasMoreTokens())
{
String tok = token.nextToken().toString();
CapLine += Character.toUpperCase(tok.charAt(0))+ tok.substring(1)+" ";
}
return CapLine.substring(0,CapLine.length()-1);
}

answered Jan 29 '14 at 6:38


foobar
1,463 1 13 33

Resuable Method for intiCap

public class YarlagaddaSireeshTest{


public static void main(String[] args) {
String FinalStringIs="";
String testNames="sireesh yarlagadda test";
String[] name=testNames.split("\\s");

for(String nameIs :name){


FinalStringIs+=getIntiCapString(nameIs)+","
;
}
System.out.println("Final Result "+ FinalStringIs);

public static String getIntiCapString(String param) {


if(param != null && param.length()>0){
char[] charArray = param.toCharArray();
charArray[0] = Character.toUpperCase(charArray[0]);
return new String(charArray);
}else{
return "";
}
}

answered Jun 13 '14 at 20:09


Sireesh Yarlagadda
5,163 1 36 46

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;

public class StringS {

/**
* @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;
}

//split string on space and create array of words


String[] arr = s.split(" ");
//create a string buffer to hold the new capitalized string
StringBuffer sb = new StringBuffer();

//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;
}

for (int i = 0; i < arr.length; i++) {


sb.append(Character.toUpperCase(arr[i].charAt(0)))
.append(arr[i].substring(1)).append(" ");
}
return sb.toString().trim();
}

answered Jan 8 '15 at 10:03


lwdthe1
189 2 8

I made a solution in Java 8 that is imho more readable.

public String firstLetterCapitalWithSingleSpace(final String words) {


return Stream.of(words.trim().split("\\s"))
.filter(word -> word.length() > 0)
.map(word -> word.substring(0, 1).toUpperCase() + word.substring(1))
.collect(Collectors.joining(" "));
}

The Gist for this solution can be found here.


https://gist.github.com/Hylke1982/166a792313c5e2df9d31

edited Feb 17 '15 at 13:28 answered Feb 17 '15 at 11:53


Hylke1982
31 2

I decided to add one more solution for capitalizing words in a string:

words are defined here as adjacent letter-or-digit characters;


surrogate pairs are provided as well;
the code has been optimized for performance; and
it is still compact.

Function:

public static String capitalize(String string) {


final int sl = string.length();
final StringBuilder sb = new StringBuilder(sl);
boolean lod = false;
for(int s = 0; s < sl; s++) {
final int cp = string.codePointAt(s);
sb.appendCodePoint(lod ? Character.toLowerCase(cp) : Character.toUpperCase(cp));
lod = Character.isLetterOrDigit(cp);
if(!Character.isBmpCodePoint(cp)) s++;
}

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:

System.out.println(capitalize("An la carte StRiNg. Surrogate pairs: ."));

Result:

An La Carte String. Surrogate Pairs: .

answered Mar 2 at 14:09


Christian Grn
3,620 7 18

Did you mean Title case?

answered Dec 12 '09 at 8:30


Shoban
20.8k 7 52 100

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.

edited Nov 12 '12 at 2:17 answered Sep 14 '11 at 0:26


ForceMagic Shogo Yahagi
3,533 8 38 70 11 1

The link is broken. Please update answer. K. Sopheak May 22 at 8:49

String s="hi dude i want apple";


s = s.replaceAll("\\s+"," ");
String[] split = s.split(" ");
s="";
for (int i = 0; i < split.length; i++) {
split[i]=Character.toUpperCase(split[i].charAt(0))+split[i].substring(1);
s+=split[i]+" ";
System.out.println(split[i]);
}
System.out.println(s);

answered Jan 2 '13 at 12:08


feel good and
programming
552 2 7 22

The Short and Precise way is as follows:

String name = "test";

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

edited May 6 '14 at 13:54 answered May 6 '14 at 13:16


Jared Burrows danielad
32.1k 16 105 136 3,833 3 31 52

this one work for Surname case.. with different type of separator, and keep the same sepator
jean-frederic --> Jean-Frederic jean frederic --> Jean Frederic

the code work with GWT client side.

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();
}

answered May 28 '14 at 16:54


jf Wastiaux
21 1

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
*/

public class Accept3Lines_FirstCharUppercase {

static String line;


static String words[];
static ArrayList<String> list=new ArrayList<String>();

/**
* @param args
*/
public static void main(String[] args) throws java.lang.Exception{

DataInputStream read=new DataInputStream(System.in);


System.out.println("Enter only three sentences");
int i=0;
while((line=read.readLine())!=null){
method(line); //main logic of the code
if((i++)==2){
break;
}
}
display();
System.out.println("\n End of the program");

/*
* 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);
}
}

edited Jul 25 '14 at 6:59 answered Jul 25 '14 at 6:56


Yu Hao Elias Sheikh
89.9k 22 141 195 11 1

If you prefer Guava...

String myString = ...;

String capWords = Joiner.on(' ').join(Iterables.transform(Splitter.on('


').omitEmptyStrings().split(myString), new Function<String, String>() {
public String apply(String input) {
return Character.toUpperCase(input.charAt(0)) + input.substring(1);
}
}));

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

answered Nov 3 '14 at 23:27


aaronvargas
5,589 2 23 24

try this

private String capitalizer(String word){

String[] words = word.split(" ");


StringBuilder sb = new StringBuilder();
if (words[0].length() > 0) {
sb.append(Character.toUpperCase(words[0].charAt(0)) + words[0].subSequence(1,
words[0].length()).toString().toLowerCase());
for (int i = 1; i < words.length; i++) {
sb.append(" ");
sb.append(Character.toUpperCase(words[i].charAt(0)) +
words[i].subSequence(1, words[i].length()).toString().toLowerCase());
}
}
return sb.toString();

edited Jul 7 '15 at 5:10 answered Jun 10 '15 at 9:31


Ameen Maheen
1,349 11 21

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.

Here is the code

/**
* @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;
}

And my toString() utility is like this

public static String getToString(Object obj)


{
StringBuilder toString = new StringBuilder();
toString.append(obj.getClass().getSimpleName());
toString.append("[");
for(Field f : obj.getClass().getDeclaredFields())
{
toString.append(f.getName());
toString.append("=");
try{
//toString.append(f.get(obj)); //access privilege issue
toString.append(invokeGetter(obj, firstCaps(f.getName()), "get"));
}
catch(Exception e)
{
e.printStackTrace();
}
toString.append(", ");
}
toString.setCharAt(toString.length()-2, ']');
return toString.toString();
}

answered Apr 1 '15 at 11:25


Parasouramane D
31 2

1 2 next

Answer This Question

https://stackoverflow.com/questions/1892765/how-to-capitalize-the-first-character-of-each-word-in-a-string 12/12

Вам также может понравиться