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

Java

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

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.

Solution 3 - Java

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

StringUtils.capitalize(Str);

Solution 4 - Java

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

StringUtils.capitalize(str);

Solution 5 - Java

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

Solution 6 - Java

Solution 7 - Java

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

}

Solution 8 - Java

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

Solution 9 - Java

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.

Solution 10 - Java

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

Solution 11 - Java

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 12 - Java

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

Solution 13 - Java

Solution with StringBuilder:

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

.. based on previous answers

Solution 14 - Java

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

Solution 15 - Java

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(" ")

Solution 16 - Java

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

Solution 17 - Java

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>

Solution 18 - Java

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

}

Solution 19 - Java

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

Solution 20 - Java

Given the input string:

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

Solution 21 - Java

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

Solution 22 - Java

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]

Solution 23 - Java

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

Solution 24 - Java

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.

Solution 25 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondiyaView Question on Stackoverflow
Solution 1 - JavaWhiteFang34View Answer on Stackoverflow
Solution 2 - JavaAntherView Answer on Stackoverflow
Solution 3 - JavaHaseebView Answer on Stackoverflow
Solution 4 - JavaIhor RybakView Answer on Stackoverflow
Solution 5 - JavaSamet ÖZTOPRAKView Answer on Stackoverflow
Solution 6 - Javaemanuel07View Answer on Stackoverflow
Solution 7 - JavaedgarmtzeView Answer on Stackoverflow
Solution 8 - JavaAvantikaView Answer on Stackoverflow
Solution 9 - JavaVismay HingwalaView Answer on Stackoverflow
Solution 10 - JavaSaurabh VermaView Answer on Stackoverflow
Solution 11 - JavaSašaView Answer on Stackoverflow
Solution 12 - JavanadaView Answer on Stackoverflow
Solution 13 - JavaGene BoView Answer on Stackoverflow
Solution 14 - JavaJeff PadgettView Answer on Stackoverflow
Solution 15 - JavaAklesh SinghView Answer on Stackoverflow
Solution 16 - JavaTakhir AtamuratovView Answer on Stackoverflow
Solution 17 - JavaChris HalcrowView Answer on Stackoverflow
Solution 18 - JavakopporView Answer on Stackoverflow
Solution 19 - JavaJason BierbrauerView Answer on Stackoverflow
Solution 20 - JavaGVillani82View Answer on Stackoverflow
Solution 21 - JavaZhifan CaiView Answer on Stackoverflow
Solution 22 - JavaRajesh PView Answer on Stackoverflow
Solution 23 - JavaVimbai ChatitaiView Answer on Stackoverflow
Solution 24 - JavaattacomsianView Answer on Stackoverflow
Solution 25 - JavaBimlendu KumarView Answer on Stackoverflow