How to capitalize the first letter of a String in Java?

JavaStringCapitalize

Java Problem Overview


I am using Java to get a String input from the user. I am trying to make the first letter of this input capitalized.

I tried this:

String name;

BufferedReader br = new InputStreamReader(System.in);

String s1 = name.charAt(0).toUppercase());

System.out.println(s1 + name.substring(1));

which led to these compiler errors:

  • > Type mismatch: cannot convert from InputStreamReader to BufferedReader

  • > Cannot invoke toUppercase() on the primitive type char

Java Solutions


Solution 1 - Java

String str = "java";
String cap = str.substring(0, 1).toUpperCase() + str.substring(1);
// cap = "Java"

With your example:

public static void main(String[] args) throws IOException {
	BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
	// Actually use the Reader
	String name = br.readLine();
	// Don't mistake String object with a Character object
	String s1 = name.substring(0, 1).toUpperCase();
	String nameCapitalized = s1 + name.substring(1);
	System.out.println(nameCapitalized);
}

Solution 2 - Java

Solution 3 - Java

The shorter/faster version code to capitalize the first letter of a String is:
String name  = "stackoverflow"; 
name = name.substring(0,1).toUpperCase() + name.substring(1).toLowerCase();

the value of name is "Stackoverflow"

Solution 4 - Java

Use Apache's common library. Free your brain from these stuffs and avoid Null Pointer & Index Out Of Bound Exceptions

Step 1:

Import apache's common lang library by putting this in build.gradle dependencies

compile 'org.apache.commons:commons-lang3:3.6'

Step 2:

If you are sure that your string is all lower case, or all you need is to initialize the first letter, directly call

StringUtils.capitalize(yourString);

If you want to make sure that only the first letter is capitalized, like doing this for an enum, call toLowerCase() first and keep in mind that it will throw NullPointerException if the input string is null.

StringUtils.capitalize(YourEnum.STUFF.name().toLowerCase());
StringUtils.capitalize(yourString.toLowerCase());

Here are more samples provided by apache. it's exception free

StringUtils.capitalize(null)  = null
StringUtils.capitalize("")    = ""
StringUtils.capitalize("cat") = "Cat"
StringUtils.capitalize("cAt") = "CAt"
StringUtils.capitalize("'cat'") = "'cat'"

Note:

WordUtils is also included in this library, but is deprecated. Please do not use that.

Solution 5 - Java

Java:

simply a helper method for capitalizing every string.

public static String capitalize(String str)
{
    if(str == null) return str;
    return str.substring(0, 1).toUpperCase() + str.substring(1);
}

After that simply call str = capitalize(str)


Kotlin:

str.capitalize()

Solution 6 - Java

if you use SPRING:

import static org.springframework.util.StringUtils.capitalize;
...


    return capitalize(name);

IMPLEMENTATION: org/springframework/util/StringUtils.java#L535-L555

REF: javadoc-api/org/springframework/util/StringUtils.html#capitalize


NOTE: If you already have Apache Common Lang dependency, then consider using their StringUtils.capitalize as other answers suggest.

Solution 7 - Java

What you want to do is probably this:

s1 = name.substring(0, 1).toUpperCase() + name.substring(1);

(converts first char to uppercase and adds the remainder of the original string)

Also, you create an input stream reader, but never read any line. Thus name will always be null.

This should work:

BufferedReader br = new InputstreamReader(System.in);
String name = br.readLine();
String s1 = name.substring(0, 1).toUpperCase() + name.substring(1);

Solution 8 - Java

Solution 9 - Java

Below solution will work.

String A = "stackOverflow";
String ACaps = A.toUpperCase().charAt(0)+A.substring(1,A.length());
//Will print StackOverflow

You can't use toUpperCase() on primitive char , but you can make entire String to Uppercase first then take the first char, then to append to the substring as shown above.

Solution 10 - Java

Solution 11 - Java

Use this utility method to get all first letter in capital.

String captializeAllFirstLetter(String name) 
{
    char[] array = name.toCharArray();
    array[0] = Character.toUpperCase(array[0]);
 
    for (int i = 1; i < array.length; i++) {
        if (Character.isWhitespace(array[i - 1])) {
            array[i] = Character.toUpperCase(array[i]);
        }
    }
 
    return new String(array);
}

Solution 12 - Java

Set the string to lower case, then set the first Letter to upper like this:

    userName = userName.toLowerCase();

then to capitalise the first letter:

    userName = userName.substring(0, 1).toUpperCase() + userName.substring(1).toLowerCase();

substring is just getting a piece of a larger string, then we are combining them back together.

Solution 13 - Java

String str1 = "hello";
str1.substring(0, 1).toUpperCase()+str1.substring(1);

Solution 14 - Java

IT WILL WORK 101%

public class UpperCase {
	
	public static void main(String [] args) {
		
		String name;
		
		System.out.print("INPUT: ");
		Scanner scan = new Scanner(System.in);
		name  = scan.next();
		
		String upperCase = name.substring(0, 1).toUpperCase() + name.substring(1);
		System.out.println("OUTPUT: " + upperCase);	
		
	}

}

Solution 15 - Java

Here is my detailed article on the topic for all possible options Capitalize First Letter of String in Android

Method to Capitalize First Letter of String in Java

public static String capitalizeString(String str) {
        String retStr = str;
        try { // We can face index out of bound exception if the string is null
            retStr = str.substring(0, 1).toUpperCase() + str.substring(1);
        }catch (Exception e){}
        return retStr;
}

Method to Capitalize First Letter of String in KOTLIN

fun capitalizeString(str: String): String {
        var retStr = str
        try { // We can face index out of bound exception if the string is null
            retStr = str.substring(0, 1).toUpperCase() + str.substring(1)
        } catch (e: Exception) {
        }
        return retStr
}

Solution 16 - Java

Shortest too:

String message = "my message";    
message = Character.toUpperCase(message.charAt(0)) + message.substring(1);
System.out.println(message)    // Will output: My message

Worked for me.

Solution 17 - Java

In Android Studio

Add this dependency to your build.gradle (Module: app)

dependencies {
    ...
    compile 'org.apache.commons:commons-lang3:3.1'
    ...
}

Now you can use

String string = "STRING WITH ALL CAPPS AND SPACES";

string = string.toLowerCase(); // Make all lowercase if you have caps

someTextView.setText(WordUtils.capitalize(string));

Solution 18 - Java

What about WordUtils.capitalizeFully()?

import org.apache.commons.lang3.text.WordUtils;

public class Main {

	public static void main(String[] args) {

		final String str1 = "HELLO WORLD";
		System.out.println(capitalizeFirstLetter(str1)); // output: Hello World

		final String str2 = "Hello WORLD";
		System.out.println(capitalizeFirstLetter(str2)); // output: Hello World

		final String str3 = "hello world";
		System.out.println(capitalizeFirstLetter(str3)); // output: Hello World

		final String str4 = "heLLo wORld";
		System.out.println(capitalizeFirstLetter(str4)); // output: Hello World
	}

	private static String capitalizeFirstLetter(String str) {
		return WordUtils.capitalizeFully(str);
	}
}

Solution 19 - Java

You can also try this:

 String s1 = br.readLine();
 char[] chars = s1.toCharArray();
 chars[0] = Character.toUpperCase(chars[0]);
 s1= new String(chars);
 System.out.println(s1);

This is better(optimized) than with using substring. (but not to worry on small string)

Solution 20 - Java

You can use substring() to do this.

But there are two different cases:

Case 1

If the String you are capitalizing is meant to be human-readable, you should also specify the default locale:

String firstLetterCapitalized = 
    myString.substring(0, 1).toUpperCase(Locale.getDefault()) + myString.substring(1);

Case 2

If the String you are capitalizing is meant to be machine-readable, avoid using Locale.getDefault() because the string that is returned will be inconsistent across different regions, and in this case always specify the same locale (for example, toUpperCase(Locale.ENGLISH)). This will ensure that the strings you are using for internal processing are consistent, which will help you avoid difficult-to-find bugs.

Note: You do not have to specify Locale.getDefault() for toLowerCase(), as this is done automatically.

Solution 21 - Java

TO get First letter capital and other wants to small you can use below code. I have done through substring function.

String currentGender="mAlE";
    currentGender=currentGender.substring(0,1).toUpperCase()+currentGender.substring(1).toLowerCase();

Here substring(0,1).toUpperCase() convert first letter capital and substring(1).toLowercase() convert all remaining letter into a small case.

OUTPUT:

Male

Solution 22 - Java

try this one

What this method does is that, Consider the word "hello world" this method turn it into "Hello World" capitalize the beginning of each word .

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

    }

Solution 23 - Java

Existing answers are either

  • incorrect: they think that char is a separate character (code point), while it is a UTF-16 word which can be a half of a surrogate pair, or
  • use libraries which is not bad itself but requires adding dependencies to your project, or
  • use Java 8 Streams which is perfectly valid but not always possible.

Let's look at surrogate characters (every such character consist of two UTF-16 words — Java chars) and can have upper and lowercase variants:

IntStream.rangeClosed(0x01_0000, 0x10_FFFF)
    .filter(ch -> Character.toUpperCase(ch) != Character.toLowerCase(ch))
    .forEach(ch -> System.out.print(new String(new int[] { ch }, 0, 1)));

Many of them may look like 'tofu' (□) for you but they are mostly valid characters of rare scripts and some typefaces support them.

For example, let's look at Deseret Small Letter Long I (Ш), U+10428, "\uD801\uDC28":

System.out.println("U+" + Integer.toHexString(
        "\uD801\uDC28".codePointAt(0)
)); // U+10428

System.out.println("U+" + Integer.toHexString(
        Character.toTitleCase("\uD801\uDC28".codePointAt(0))
)); // U+10400 — ok! capitalized character is another code point

System.out.println("U+" + Integer.toHexString(new String(new char[] {
        Character.toTitleCase("\uD801\uDC28".charAt(0)), "\uD801\uDC28".charAt(1)
}).codePointAt(0))); // U+10428 — oops! — cannot capitalize an unpaired surrogate

So, a code point can be capitalized even in cases when char cannot be. Considering this, let's write a correct (and Java 1.5 compatible!) capitalizer:

@Contract("null -> null")
public static CharSequence capitalize(CharSequence input) {
    int length;
    if (input == null || (length = input.length()) == 0) return input;

    return new StringBuilder(length)
            .appendCodePoint(Character.toTitleCase(Character.codePointAt(input, 0)))
            .append(input, Character.offsetByCodePoints(input, 0, 1), length);
}

And check whether it works:

public static void main(String[] args) {
    // ASCII
    System.out.println(capitalize("whatever")); // w -> W

    // UTF-16, no surrogate
    System.out.println(capitalize("что-то")); // ч -> Ч

    // UTF-16 with surrogate pairs
    System.out.println(capitalize("\uD801\uDC28")); // 𐐨 -> 𐐀
}

See also:

Solution 24 - Java

Current answers are either incorrect or over-complicate this simple task. After doing some research, here are two approaches I come up with:

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

Examples:

System.out.println(capitalize("java")); // Java
System.out.println(capitalize("beTa")); // BeTa
System.out.println(capitalize(null)); // null

2. Apache Commons Lang

The Apache Commons Lang library provides StringUtils the class 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

Don't forget to add the following dependency to your pom.xml file:

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

Solution 25 - Java

Simple solution! doesn't require any external library, it can handle empty or one letter string.

private String capitalizeFirstLetter(@NonNull  String str){
        return str.length() == 0 ? str
                : str.length() == 1 ? str.toUpperCase()
                : str.substring(0, 1).toUpperCase() + str.substring(1).toLowerCase();
}

Solution 26 - Java

This is just to show you, that you were not that wrong.

BufferedReader br = new InputstreamReader(System.in);
// Assuming name is not blank
String name = br.readLine(); 

//No more error telling that you cant convert char to string
String s1 = (""+name.charAt(0)).toUppercase());
// Or, as Carlos prefers. See the comments to this post.
String s1 = Character.toString(name.charAt(0)).toUppercase());

System.out.println(s1+name.substring(1));

Note: This is not at all the best way to do it. This is just to show the OP that it can be done using charAt() as well. ;)

Solution 27 - Java

This will work

char[] array = value.toCharArray();

array[0] = Character.toUpperCase(array[0]);

String result = new String(array);

Solution 28 - Java

You can use the following code:

public static void main(String[] args) {

	capitalizeFirstLetter("java");
	capitalizeFirstLetter("java developer");
}

public static void capitalizeFirstLetter(String text) {

	StringBuilder str = new StringBuilder();

	String[] tokens = text.split("\\s");// Can be space,comma or hyphen

	for (String token : tokens) {
		str.append(Character.toUpperCase(token.charAt(0))).append(token.substring(1)).append(" ");
	}
	str.toString().trim(); // Trim trailing space

	System.out.println(str);

}

Solution 29 - Java

Using commons.lang.StringUtils the best answer is:

public static String capitalize(String str) {  
    int strLen;  
    return str != null && (strLen = str.length()) != 0 ? (new StringBuffer(strLen)).append(Character.toTitleCase(str.charAt(0))).append(str.substring(1)).toString() : str;  
}

I find it brilliant since it wraps the string with a StringBuffer. You can manipulate the StringBuffer as you wish and though using the same instance.

Solution 30 - Java

If Input is UpperCase ,then Use following :

str.substring(0, 1).toUpperCase() + str.substring(1).toLowerCase();

If Input is LowerCase ,then Use following :

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

Solution 31 - Java

Have a look at ACL WordUtils.

WordUtils.capitalize("your string") == "Your String"

https://stackoverflow.com/questions/1149855/how-to-upper-case-every-first-letter-of-word-in-a-string

Solution 32 - Java

public static String capitalizer(final String texto) {

	// split words
	String[] palavras = texto.split(" ");
	StringBuilder sb = new StringBuilder();

    // list of word exceptions
	List<String> excessoes = new ArrayList<String>(Arrays.asList("de", "da", "das", "do", "dos", "na", "nas", "no", "nos", "a", "e", "o", "em", "com"));

	for (String palavra : palavras) {

		if (excessoes.contains(palavra.toLowerCase()))
			sb.append(palavra.toLowerCase()).append(" ");
		else
            sb.append(Character.toUpperCase(palavra.charAt(0))).append(palavra.substring(1).toLowerCase()).append(" ");
	}
	return sb.toString().trim();
}

Solution 33 - Java

You can use the following code:

public static String capitalizeString(String string) {

	if (string == null || string.trim().isEmpty()) {
		return string;
	}
	char c[] = string.trim().toLowerCase().toCharArray();
	c[0] = Character.toUpperCase(c[0]);

	return new String(c);

}

example test with JUnit:

@Test
public void capitalizeStringUpperCaseTest() {

	String string = "HELLO WORLD  ";

	string = capitalizeString(string);

	assertThat(string, is("Hello world"));
}

@Test
public void capitalizeStringLowerCaseTest() {

	String string = "hello world  ";

	string = capitalizeString(string);

	assertThat(string, is("Hello world"));
}

Solution 34 - Java

You can use substrings for simple hacks ;).

String name;
    
String s1 = name.substring(0, 1).toUpperCase() + name.substring(1, name.length());

System.out.println(s1));

Solution 35 - Java

System.out.println(Character.toString(A.charAt(0)).toUpperCase()+A.substring(1));

P.S = a is a string.

Solution 36 - Java

Yet another example, how you can make the first letter of the user input capitalized:

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String string = br.readLine();
// handle supplementary characters
IntStream.concat(
		IntStream.of(string.codePointAt(0))
				.map(Character::toUpperCase), string.codePoints().skip(1)
)
.forEach(cp -> System.out.print(Character.toChars(cp)));

Solution 37 - Java

Since you first get Char from your original string. You cant use String properties on char so just use to upper first and then use charAt

String s1 = name.toUppercase().charAt(0);

Solution 38 - Java

Many of the answers are very helpful so I used them to create a method to turn any string to a title (first character capitalized):

static String toTitle (String s) {
      String s1 = s.substring(0,1).toUpperCase();
      String sTitle = s1 + s.substring(1);
      return sTitle;
 }

Solution 39 - Java

Just reworked Jorgesys code and added few checks because of few cases related to String length. Don't do for null reference check in my case.

 public static String capitalizeFirstLetter(@NonNull String customText){
        int count = customText.length();
        if (count == 0) {
            return customText;
        }
        if (count == 1) {
            return customText.toUpperCase();
        }
        return customText.substring(0, 1).toUpperCase() + customText.substring(1).toLowerCase();
    }

Solution 40 - Java

To capitalize first character of each word in a string ,

first you need to get each words of that string & for this split string where any space is there using split method as below and store each words in an Array. Then create an empty string. After that by using substring() method get the first character & remaining character of corresponding word and store them in two different variables.

Then by using toUpperCase() method capitalize the first character and add the remaianing characters as below to that empty string.

public class Test {  
     public static void main(String[] args)
     {
         String str= "my name is khan";        // string
         String words[]=str.split("\\s");      // split each words of above string
         String capitalizedWord = "";         // create an empty string
    
         for(String w:words)
         {  
              String first = w.substring(0,1);    // get first character of each word
              String f_after = w.substring(1);    // get remaining character of corresponding word
              capitalizedWord += first.toUpperCase() + f_after+ " ";  // capitalize first character and add the remaining to the empty string and continue
         }
         System.out.println(capitalizedWord);    // print the result
     }
}

Solution 41 - Java

The code i have posted will remove underscore(_) symbol and extra spaces from String and also it will capitalize first letter of every new word in String

private String capitalize(String txt){ 
  List<String> finalTxt=new ArrayList<>();

  if(txt.contains("_")){
       txt=txt.replace("_"," ");
  }

  if(txt.contains(" ") && txt.length()>1){
       String[] tSS=txt.split(" ");
       for(String tSSV:tSS){ finalTxt.add(capitalize(tSSV)); }  
  }

  if(finalTxt.size()>0){
       txt="";
       for(String s:finalTxt){ txt+=s+" "; }
  }

  if(txt.endsWith(" ") && txt.length()>1){
       txt=txt.substring(0, (txt.length()-1));
       return txt;
  }

  txt = txt.substring(0,1).toUpperCase() + txt.substring(1).toLowerCase();
  return txt;
}

Solution 42 - Java

One of the answers was 95% correct, but it failed on my unitTest @Ameen Maheen's solution was nearly perfect. Except that before the input gets converted to String array, you have to trim the input. So the perfect one:

private String convertStringToName(String name) {
        name = name.trim();
        String[] words = name.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();
    }

Solution 43 - Java

Given answers is for capitalize the first letter of one word only. use following code to capitalize a whole string.

public static void main(String[] args) {
	String str = "this is a random string";
	StringBuilder capitalizedString = new StringBuilder();
	String[] splited = str.trim().split("\\s+");
	
	for (String string : splited) {			
		String s1 = string.substring(0, 1).toUpperCase();
	    String nameCapitalized = s1 + string.substring(1);
	    		    
	    capitalizedString.append(nameCapitalized);
	    capitalizedString.append(" ");
	}
	System.out.println(capitalizedString.toString().trim());
}

output : This Is A Random String

Solution 44 - Java

Use replace method.

String newWord = word.replace(String.valueOf(word.charAt(0)), String.valueOf(word.charAt(0)).toUpperCase());

Solution 45 - Java

To capitalize the first letter of the input string, we first split the string on space and then use the collection transformation procedure provided by map

<T, R> Array<out T>.map(

   transform: (T) -> R

): List<R>

to transform, each split string to first in lowercase then capitalize the first letter. This map transformation will return a list that needs to convert into a string by using joinToString function.

> KOTLIN

fun main() {
    
    /*
     * Program that first convert all uper case into lower case then 
     * convert fist letter into uppercase
     */
    
    val str = "aLi AzAZ alam"
    val calStr = str.split(" ").map{it.toLowerCase().capitalize()}
    println(calStr.joinToString(separator = " "))
}

> OUTPUT

output of above code

Solution 46 - Java

Following example also capitalizes words after special characters such as [/-]

  public static String capitalize(String text) {
    char[] stringArray = text.trim().toCharArray();
    boolean wordStarted = false;
    for( int i = 0; i < stringArray.length; i++) {
      char ch = stringArray[i];
      if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || ch == '\'') {
        if( !wordStarted ) {
          stringArray[i] = Character.toUpperCase(stringArray[i]);
          wordStarted = true;
        } 
      } else {
        wordStarted = false;
      }
    }
    return new String(stringArray);
  }

Example:
capitalize("that's a beautiful/wonderful life we have.We really-do")

Output:
That's A Beautiful/Wonderful Life We Have.We Really-Do

Solution 47 - Java

thanks I have read some of the comments and I came with the following

public static void main(String args[]) 
{
String myName = "nasser";
String newName = myName.toUpperCase().charAt(0) +  myName.substring(1);
System.out.println(newName );
}

I hope its helps good luck

Solution 48 - Java

The answer from Ameen Mahheen is good but if we have some string with double space, like "hello world" then sb.append gets IndexOutOfBounds Exception. Right thing to do is teste before this line, doing:

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(" ");
            	if (words[i].length() > 0) sb.append(Character.toUpperCase(words[i].charAt(0)) + words[i].subSequence(1, words[i].length()).toString().toLowerCase());
            }
        }
        return  sb.toString();
    }

Solution 49 - Java

You may try this

/**
 * capitilizeFirst(null)  -> ""
 * capitilizeFirst("")    -> ""
 * capitilizeFirst("   ") -> ""
 * capitilizeFirst(" df") -> "Df"
 * capitilizeFirst("AS")  -> "As"
 *
 * @param str input string
 * @return String with the first letter capitalized
 */
public String capitilizeFirst(String str)
{
    // assumptions that input parameter is not null is legal, as we use this function in map chain
    Function<String, String> capFirst = (String s) -> {
        String result = ""; // <-- accumulator

        try { result += s.substring(0, 1).toUpperCase(); }
        catch (Throwable e) {}
        try { result += s.substring(1).toLowerCase(); }
        catch (Throwable e) {}

        return result;
    };

    return Optional.ofNullable(str)
            .map(String::trim)
            .map(capFirst)
            .orElse("");
}

Solution 50 - Java

You can use Class WordUtils.

Suppose your String is "current address" then use

****strong textWordutils.capitaliz(String); output : Current Address

Refer: http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/text/WordUtils.html

Solution 51 - Java

class CapitalizeWords
{
	public static void main(String[] args) 
	{
		String input ="welcome to kashmiri geeks...";
	
		System.out.println(input);
		
		String[] str = input.split(" ");

		for(int i=0; i< str.length; i++)
		{
			str[i] = (str[i]).substring(0,1).toUpperCase() + (str[i]).substring(1);
		}

		for(int i=0;i<str.length;i++)
		{
			System.out.print(str[i]+" ");
		}
		

	}
}

Solution 52 - Java

String s = "first second third fourth";
       
        int j = 0;
        for (int i = 0; i < s.length(); i++) {

            if ((s.substring(j, i).endsWith(" "))) {

                String s2 = s.substring(j, i);
                System.out.println(Character.toUpperCase(s.charAt(j))+s2.substring(1));
                j = i;
            }
        }
        System.out.println(Character.toUpperCase(s.charAt(j))+s.substring(j+1));

Solution 53 - Java

One approach.

String input = "someТекст$T%$4čřЭ"; //Enter your text.
if (input == null || input.isEmpty()) {
    return "";
}

char [] chars = input.toCharArray();
chars[0] = chars[0].toUpperCase();
String res = new String(chars);
return res;

The drawback of this method is that if inputString is long, you will have three objects of such length. The same as you do

String s1 = input.substring(1).toUpperCase();
String s2 = input.substring(1, lenght);
String res = s1 + s2;

Or even

//check if not null.
StringBuilder buf = new StringBuilder(input);
char ch = buf.getCharAt(0).toUpperCase();
buf.setCharAt(0, ch);
return buf.toString();

Solution 54 - Java

This code to capitalize each word in text!

public String capitalizeText(String name) {
    String[] s = name.trim().toLowerCase().split("\\s+");
    name = "";
    for (String i : s){
        if(i.equals("")) return name; // or return anything you want
        name+= i.substring(0, 1).toUpperCase() + i.substring(1) + " "; // uppercase first char in words
    }
    return name.trim();
}

Solution 55 - Java

import java.util.*;
public class Program
{
	public static void main(String[] args) 
      {
        Scanner sc=new Scanner(System.in);
        String s1=sc.nextLine();
        String[] s2=s1.split(" ");//***split text into words***
        ArrayList<String> l = new ArrayList<String>();//***list***
	    for(String w: s2)
        l.add(w.substring(0,1).toUpperCase()+w.substring(1)); 
        //***converting 1st letter to capital and adding to list***
        StringBuilder sb = new StringBuilder();//***i used StringBuilder to convert words to text*** 
        for (String s : l)
          {
             sb.append(s);
             sb.append(" ");
          }
      System.out.println(sb.toString());//***to print output***
      }
}

i have used split function to split the string into words then again i took list to get the first letter capital in that words and then i took string builder to print the output in string format with spaces in it

Solution 56 - Java

Here is solution from my side, with all the conditions check.

   import java.util.Objects;

public class CapitalizeFirstCharacter {

	public static void main(String[] args) {

		System.out.println(capitailzeFirstCharacterOfString("jwala")); //supply input string here
	}

	private static String capitailzeFirstCharacterOfString(String strToCapitalize) {

		if (Objects.nonNull(strToCapitalize) && !strToCapitalize.isEmpty()) {
			return strToCapitalize.substring(0, 1).toUpperCase() + strToCapitalize.substring(1);
		} else {
			return "Null or Empty value of string supplied";

		}

	}

}

Solution 57 - Java

  1. If you want to capitalize only first letter, Use this code:

    fun capitalizeFirstLetter(str: String): String {
    return when {
        str.isEmpty() -> str
        str.length == 1 -> str.uppercase(Locale.getDefault())
        else -> str.substring(0, 1)
            .uppercase(Locale.getDefault()) + str.substring(1)
            .lowercase(Locale.getDefault())
    }
    

    }

  2. If you want to capitalize every first letter of word in Sentence Use this code:

    fun capitalizeEveryFirstLetterOfWordInSentence(str: String): String {
    return when {
        str.isEmpty() -> str
        str.length == 1 -> str.uppercase(Locale.getDefault())
        else -> str
            .lowercase(Locale.getDefault())
            .split(" ")
            .joinToString(" ") { it ->
                it.replaceFirstChar {
                    if (it.isLowerCase()) it.titlecase(Locale.getDefault())
                    else it.toString()
                }
            }.trimEnd()
    }}
    

3.Then, simply call function and pass value like this:

capitalizeFirstLetter("your String")
capitalizeEveryFirstLetterOfWordInSentence("your String")

Solution 58 - Java

Those who search capitalize first letter of a name here..

public static String capitaliseName(String name) {
    String collect[] = name.split(" ");
    String returnName = "";
    for (int i = 0; i < collect.length; i++) {
        collect[i] = collect[i].trim().toLowerCase();
        if (collect[i].isEmpty() == false) {
            returnName = returnName + collect[i].substring(0, 1).toUpperCase() + collect[i].substring(1) + " ";
        }
    }
    return returnName.trim();
}

> usase: capitaliseName("saurav khan"); > > output: Saurav Khan

Solution 59 - Java

Try this, it worked for me.

public static String capitalizeName(String name) {
    String fullName = "";
    String names[] = name.split(" ");
    for (String n: names) {
        fullName = fullName + n.substring(0, 1).toUpperCase() + n.toLowerCase().substring(1, n.length()) + " ";
    }
    return fullName;
}

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
QuestionsumithraView Question on Stackoverflow
Solution 1 - JavaRekinView Answer on Stackoverflow
Solution 2 - JavaBozhoView Answer on Stackoverflow
Solution 3 - JavaJorgesysView Answer on Stackoverflow
Solution 4 - JavaFangmingView Answer on Stackoverflow
Solution 5 - JavaAmir Hossein GhasemiView Answer on Stackoverflow
Solution 6 - JavaepoxView Answer on Stackoverflow
Solution 7 - JavaGrodriguezView Answer on Stackoverflow
Solution 8 - JavaZakiView Answer on Stackoverflow
Solution 9 - JavaJijil KakkadathuView Answer on Stackoverflow
Solution 10 - JavaSuresh KumarView Answer on Stackoverflow
Solution 11 - JavaKrishnaView Answer on Stackoverflow
Solution 12 - JavaAlexZeCoderView Answer on Stackoverflow
Solution 13 - JavaAditya ParmarView Answer on Stackoverflow
Solution 14 - JavaUTTAMView Answer on Stackoverflow
Solution 15 - JavaAsad Ali ChoudhryView Answer on Stackoverflow
Solution 16 - JavaDassi OrleandoView Answer on Stackoverflow
Solution 17 - JavaMichaelView Answer on Stackoverflow
Solution 18 - JavaArpit AggarwalView Answer on Stackoverflow
Solution 19 - JavajerjerView Answer on Stackoverflow
Solution 20 - JavaJDJView Answer on Stackoverflow
Solution 21 - JavaNimesh PatelView Answer on Stackoverflow
Solution 22 - JavaAmeen MaheenView Answer on Stackoverflow
Solution 23 - JavaMiha_x64View Answer on Stackoverflow
Solution 24 - JavaattacomsianView Answer on Stackoverflow
Solution 25 - JavaH4SNView Answer on Stackoverflow
Solution 26 - JavaAdeel AnsariView Answer on Stackoverflow
Solution 27 - JavaMohamed Abdullah JView Answer on Stackoverflow
Solution 28 - Javauser5150135View Answer on Stackoverflow
Solution 29 - JavavelocityView Answer on Stackoverflow
Solution 30 - JavaRaj KumarView Answer on Stackoverflow
Solution 31 - JavaManoj EkanayakaView Answer on Stackoverflow
Solution 32 - JavaDoc BrownView Answer on Stackoverflow
Solution 33 - JavaDavid Navarro AstudilloView Answer on Stackoverflow
Solution 34 - JavaSureshView Answer on Stackoverflow
Solution 35 - JavaGerma VinsmokeView Answer on Stackoverflow
Solution 36 - Javauser1134181View Answer on Stackoverflow
Solution 37 - JavaHeadShot191View Answer on Stackoverflow
Solution 38 - JavaNooblhuView Answer on Stackoverflow
Solution 39 - JavaRuslan PoduretsView Answer on Stackoverflow
Solution 40 - JavaDcoder14View Answer on Stackoverflow
Solution 41 - JavaShehrozEKView Answer on Stackoverflow
Solution 42 - JavacrixView Answer on Stackoverflow
Solution 43 - JavaVimukthiView Answer on Stackoverflow
Solution 44 - JavaEngineView Answer on Stackoverflow
Solution 45 - JavaAli Azaz AlamView Answer on Stackoverflow
Solution 46 - JavaDeloreanView Answer on Stackoverflow
Solution 47 - JavaNasser Al kaabiView Answer on Stackoverflow
Solution 48 - JavaRaphael MoraesView Answer on Stackoverflow
Solution 49 - JavaRoman GordeevView Answer on Stackoverflow
Solution 50 - JavaSANDEEP KIRWAIView Answer on Stackoverflow
Solution 51 - JavaMaahi bhatView Answer on Stackoverflow
Solution 52 - Javaemre hamurcuView Answer on Stackoverflow
Solution 53 - JavaYan KhonskiView Answer on Stackoverflow
Solution 54 - JavaAn Van NguyenView Answer on Stackoverflow
Solution 55 - JavaSindhu AdapaView Answer on Stackoverflow
Solution 56 - JavaJwala KumarView Answer on Stackoverflow
Solution 57 - JavaMuzammil HussainView Answer on Stackoverflow
Solution 58 - JavaMahbubur Rahman KhanView Answer on Stackoverflow
Solution 59 - JavaCaio Cesar FantiniView Answer on Stackoverflow