[java] How to capitalize the first letter of word in a string using Java?

Example strings

one thousand only
two hundred
twenty
seven

How do I change the first character of a string in capital letter and not change the case of any of the other letters?

After the change it should be:

One thousand only
Two hundred
Twenty
Seven

Note: I don't want to use the apache.commons.lang.WordUtils to do this.

This question is related to java

The answer is


public static String capitalize(String str){
        String[] inputWords = str.split(" ");
        String outputWords = "";
        for (String word : inputWords){
            if (!word.isEmpty()){
                outputWords = outputWords + " "+StringUtils.capitalize(word);
            }
        }
        return outputWords;
    }

My functional approach. its capstilise first character in sentence after whitescape in whole paragraph.

For capatilising only first character of the word just remove .split(" ")

           b.name.split(" ")
                 .filter { !it.isEmpty() }
                 .map { it.substring(0, 1).toUpperCase() 
                 +it.substring(1).toLowerCase() }
                  .joinToString(" ")

if you only want to capitalize the first letter then the below code can be used

String output = input.substring(0, 1).toUpperCase() + input.substring(1);

The following will give you the same consistent output regardless of the value of your inputString:

if(StringUtils.isNotBlank(inputString)) {
    inputString = StringUtils.capitalize(inputString.toLowerCase());
}


public String capitalizeFirstLetter(String original) {
    if (original == null || original.length() == 0) {
        return original;
    }
    return original.substring(0, 1).toUpperCase() + original.substring(1);
}

Just... a complete solution, I see it kind of just ended up combining what everyone else ended up posting =P.


Example using StringTokenizer class :

String st = "  hello all students";
String st1;
char f;
String fs="";
StringTokenizer a= new StringTokenizer(st);
while(a.hasMoreTokens()){   
        st1=a.nextToken();
        f=Character.toUpperCase(st1.charAt(0));
        fs+=f+ st1.substring(1);
        System.out.println(fs);
} 

Adding everything together, it is a good idea to trim for extra white space at beginning of string. Otherwise, .substring(0,1).toUpperCase will try to capitalize a white space.

    public String capitalizeFirstLetter(String original) {
        if (original == null || original.length() == 0) {
            return original;
        }
        return original.trim().substring(0, 1).toUpperCase() + original.substring(1);
    }

String s=t.getText().trim();
int l=s.length();
char c=Character.toUpperCase(s.charAt(0));
s=c+s.substring(1);
for(int i=1; i<l; i++)
    {
        if(s.charAt(i)==' ')
        {
            c=Character.toUpperCase(s.charAt(i+1));
            s=s.substring(0, i) + c + s.substring(i+2);
        }
    }
    t.setText(s);

Given the input string:

Character.toUpperCase(input.charAt(0)) + input.substring(1).toLowerCase()

Its simple only one line code is needed for this. if String A = scanner.nextLine(); then you need to write this to display the string with this first letter capitalized.

System.out.println(A.substring(0, 1).toUpperCase() + A.substring(1));

And its done now.


class Test {
     public static void main(String[] args) {
        String newString="";
        String test="Hii lets cheCk for BEING String";  
        String[] splitString = test.split(" ");
        for(int i=0; i<splitString.length; i++){
            newString= newString+ splitString[i].substring(0,1).toUpperCase() 
                    + splitString[i].substring(1,splitString[i].length()).toLowerCase()+" ";
        }
        System.out.println("the new String is "+newString);
    }
 }

Use this:

char[] chars = {Character.toUpperCase(A.charAt(0)), 
Character.toUpperCase(B.charAt(0))};
String a1 = chars[0] + A.substring(1);
String b1 = chars[1] + B.substring(1);

Simplest way is to use org.apache.commons.lang.StringUtils class

StringUtils.capitalize(Str);


Also, There is org.springframework.util.StringUtils in Spring Framework:

StringUtils.capitalize(str);

Here you go (hope this give you the idea):

/*************************************************************************
 *  Compilation:  javac Capitalize.java
 *  Execution:    java Capitalize < input.txt
 * 
 *  Read in a sequence of words from standard input and capitalize each
 *  one (make first letter uppercase; make rest lowercase).
 *
 *  % java Capitalize
 *  now is the time for all good 
 *  Now Is The Time For All Good 
 *  to be or not to be that is the question
 *  To Be Or Not To Be That Is The Question 
 *
 *  Remark: replace sequence of whitespace with a single space.
 *
 *************************************************************************/

public class Capitalize {

    public static String capitalize(String s) {
        if (s.length() == 0) return s;
        return s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
    }

    public static void main(String[] args) {
        while (!StdIn.isEmpty()) {
            String line = StdIn.readLine();
            String[] words = line.split("\\s");
            for (String s : words) {
                StdOut.print(capitalize(s) + " ");
            }
            StdOut.println();
        }
    }

}

Actually, you will get the best performance if you avoid + operator and use concat() in this case. It is the best option for merging just 2 strings (not so good for many strings though). In that case the code would look like this:

String output = input.substring(0, 1).toUpperCase().concat(input.substring(1));

Solution with StringBuilder:

value = new StringBuilder()
                .append(value.substring(0, 1).toUpperCase())
                .append(value.substring(1))
                .toString();

.. based on previous answers


1. Using String's substring() Method

public static String capitalize(String str) {
    if(str== null || str.isEmpty()) {
        return str;
    }

    return str.substring(0, 1).toUpperCase() + str.substring(1);
}

Now just call the capitalize() method to convert the first letter of a string to uppercase:

System.out.println(capitalize("stackoverflow")); // Stackoverflow
System.out.println(capitalize("heLLo")); // HeLLo
System.out.println(capitalize(null)); // null

2. Apache Commons Lang

The StringUtils class from Commons Lang provides the capitalize() method that can also be used for this purpose:

System.out.println(StringUtils.capitalize("apache commons")); // Apache commons
System.out.println(StringUtils.capitalize("heLLO")); // HeLLO
System.out.println(StringUtils.uncapitalize(null)); // null

Add the following dependency to your pom.xml file (for Maven only):

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.9</version>
</dependency>

Here is an article that explains these two approaches in detail.


I would like to add a NULL check and IndexOutOfBoundsException on the accepted answer.

String output = input.substring(0, 1).toUpperCase() + input.substring(1);

Java Code:

  class Main {
      public static void main(String[] args) {
        System.out.println("Capitalize first letter ");
        System.out.println("Normal  check #1      : ["+ captializeFirstLetter("one thousand only")+"]");
        System.out.println("Normal  check #2      : ["+ captializeFirstLetter("two hundred")+"]");
        System.out.println("Normal  check #3      : ["+ captializeFirstLetter("twenty")+"]");
        System.out.println("Normal  check #4      : ["+ captializeFirstLetter("seven")+"]");

        System.out.println("Single letter check   : ["+captializeFirstLetter("a")+"]");
        System.out.println("IndexOutOfBound check : ["+ captializeFirstLetter("")+"]");
        System.out.println("Null Check            : ["+ captializeFirstLetter(null)+"]");
      }

      static String captializeFirstLetter(String input){
             if(input!=null && input.length() >0){
                input = input.substring(0, 1).toUpperCase() + input.substring(1);
            }
            return input;
        }
    }

Output:

Normal  check #1      : [One thousand only]
Normal  check #2      : [Two hundred]
Normal  check #3      : [Twenty]
Normal  check #4      : [Seven]
Single letter check   : [A]
IndexOutOfBound check : []
Null Check            : [null]

You can try the following code:

public string capitalize(str) {
    String[] array = str.split(" ");
    String newStr;
    for(int i = 0; i < array.length; i++) {
        newStr += array[i].substring(0,1).toUpperCase() + array[i].substring(1) + " ";
    }
    return newStr.trim();
}

String sentence = "ToDAY   WeAthEr   GREat";    
public static String upperCaseWords(String sentence) {
        String words[] = sentence.replaceAll("\\s+", " ").trim().split(" ");
        String newSentence = "";
        for (String word : words) {
            for (int i = 0; i < word.length(); i++)
                newSentence = newSentence + ((i == 0) ? word.substring(i, i + 1).toUpperCase(): 
                    (i != word.length() - 1) ? word.substring(i, i + 1).toLowerCase() : word.substring(i, i + 1).toLowerCase().toLowerCase() + " ");
        }

        return newSentence;
    }
//Today Weather Great

Even for "simple" code, I would use libraries. The thing is not the code per se, but the already existing test cases covering exceptional cases. This could be null, empty strings, strings in other languages.

The word manipulation part has been moved out ouf Apache Commons Lang. It is now placed in Apache Commons Text. Get it via https://search.maven.org/artifact/org.apache.commons/commons-text.

You can use WordUtils.capitalize(String str) from Apache Commons Text. It is more powerful than you asked for. It can also capitalize fulle (e.g., fixing "oNe tousand only").

Since it works on complete text, one has to tell it to capitalize only the first word.

WordUtils.capitalize("one thousand only", new char[0]);

Full JUnit class to enable playing with the functionality:

package io.github.koppor;

import org.apache.commons.text.WordUtils;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.*;

class AppTest {

  @Test
  void test() {
    assertEquals("One thousand only", WordUtils.capitalize("one thousand only", new char[0]));
  }

}

Update July 2019

Currently, the most up-to-date library function for doing this is contained in org.apache.commons.lang3.StringUtils

import org.apache.commons.lang3.StringUtils;

StringUtils.capitalize(myString);

If you're using Maven, import the dependency in your pom.xml:

<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-lang3</artifactId>
  <version>3.9</version>
</dependency>