235

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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
diya
  • 6,938
  • 9
  • 39
  • 55
  • 1
    @eat_a_lemon: much better to use Character.toUpperCase(), as it deals with cases other than a-z (e.g. numbers, punctuation, letters with diacritics, non-Latin characters). – Simon Nickerson Apr 20 '11 at 05:40
  • 1
    related: http://stackoverflow.com/questions/1149855/ – ManBugra May 05 '11 at 13:28

24 Answers24

557

If you only want to capitalize the first letter of a string named input and leave the rest alone:

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

Now output will have what you want. Check that your input is at least one character long before using this, otherwise you'll get an exception.

WhiteFang34
  • 70,765
  • 18
  • 106
  • 111
  • 39
    Also, I would first take the entire input and make it lower-case or rework your example as follows: String output = input.substring(0, 1).toUpperCase() + input.substring(1).toLowerCase(); – David Brossard Oct 30 '13 at 10:48
  • 2
    And you want to check the length of the string, as it could be 1 letter string, or even 0. – Marek Oct 06 '17 at 14:18
  • 1
    I found this here for getter and setter name creation, therefore to LowerCase on the rest of the String will break the field naming. Given answer is perfect for me. – kaiser Aug 27 '19 at 08:47
90
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.

Mike
  • 8,137
  • 6
  • 28
  • 46
Anther
  • 1,834
  • 12
  • 13
  • 12
    Nice. I "one-linered" it: `return original.length() == 0 ? original : original.substring(0, 1).toUpperCase() + original.substring(1);` – mharper Sep 20 '13 at 21:13
  • 4
    @mharper: `if length() == 0`, can't we safely say that it's `""` and return that instead of `original`? Saves us a few characters in a one-liner. I ask because I feel like Java is a language so full of gotcha's, I honestly wouldn't be surprised if there was some other way to have a string of length zero. – ArtOfWarfare Mar 03 '15 at 20:24
  • You speak all truth @ArtOfWarfare. – mharper Mar 04 '15 at 04:30
  • 1
    Note: you may also want to make this working with non-english letters. In that case you should specify locale in toUpperCase() method. – Makalele Sep 29 '16 at 12:59
  • It's not possible to use `String.toUpperCase(Locale)` for an arbitrary string, because the Locale has to match the text. Yes, it should be used, but it's not always clear which `Locale` to use... – Christopher Schultz Jul 12 '19 at 21:10
87

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

StringUtils.capitalize(Str);

Haseeb
  • 1,124
  • 8
  • 12
  • 9
    Little side-note here. It works only for strings that are not already capitalized. – jobbert May 09 '16 at 13:49
  • 6
    @jobbert Please clarify your comment. If the strings are already capitalized, will it uncapitalized those despite being a method named `capitalize`? – Cœur Jul 11 '18 at 16:49
  • [According to the docs](http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#capitalize-java.lang.String-) only the first character is changed, so this is only helpful if you can predict your input well enough to know there are no other chars that may be uppercase. – gekkedev Dec 26 '20 at 21:25
28

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

StringUtils.capitalize(str);
Ihor Rybak
  • 3,091
  • 2
  • 25
  • 32
8
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
Samet ÖZTOPRAK
  • 3,112
  • 3
  • 32
  • 33
7

StringUtils.capitalize(str)

from apache commons-lang.

Paul Rooney
  • 20,879
  • 9
  • 40
  • 61
emanuel07
  • 738
  • 12
  • 27
3
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);
Community
  • 1
  • 1
Avantika
  • 31
  • 1
  • 2
    This will uppercase the first letter of *each* word, not of the string as a whole. See the examples provided by OP. Also there could be problems if there is a space at the end of the string. – tobias_k Sep 25 '12 at 16:47
3

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

}
edgarmtze
  • 24,683
  • 80
  • 235
  • 386
3

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));
Saša
  • 4,416
  • 1
  • 27
  • 41
2

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.

1

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);
} 
Imran Ali
  • 2,223
  • 2
  • 28
  • 41
nada
  • 11
  • 1
1

Solution with StringBuilder:

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

.. based on previous answers

Gene Bo
  • 11,284
  • 8
  • 90
  • 137
1

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);
    }
Jeff Padgett
  • 2,380
  • 22
  • 34
1

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(" ")
Aklesh Singh
  • 917
  • 10
  • 12
1
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;
    }
1

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>
Chris Halcrow
  • 28,994
  • 18
  • 176
  • 206
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());
}
1

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

}
koppor
  • 19,079
  • 15
  • 119
  • 161
0

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);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
0

Given the input string:

Character.toUpperCase(input.charAt(0)) + input.substring(1).toLowerCase()
GVillani82
  • 17,196
  • 30
  • 105
  • 172
0

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

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]
Hardian
  • 1,922
  • 22
  • 23
0

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.

attacomsian
  • 2,667
  • 23
  • 24
-1
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);
    }
 }
Matthias A. Eckhart
  • 5,136
  • 4
  • 27
  • 34
Bimlendu Kumar
  • 226
  • 2
  • 17