Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

People also ask

How do you capitalize the first word in a string?

To capitalize the first character of a string, We can use the charAt() to separate the first character and then use the toUpperCase() function to capitalize it.

How do you capitalize words in Java?

You can capitalize words in a string using the toUpperCase() method of the String class. This method converts the contents of the current string to Upper case letters.

Do you capitalize string in Java?

Java - String toUpperCase() Method The first variant converts all of the characters in this String to upper case using the rules of the given Locale. This is equivalent to calling toUpperCase(Locale.

How do you start a sentence with a word with a capital letter in Java?

We can easily convert the first letter of each word of a string into uppercase by splitting the sentence into words (words array) using the split() method and applying toUpperCase() on each word.


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.


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.


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

StringUtils.capitalize(str)

from apache commons-lang.


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

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