Java string to capitalize first letter

Capitalize the first letter of a string in Java

In this quick tutorial, you will learn how to capitalize the first letter of a string in Java. Unfortunately, the String class does not provide any method to capitalize strings. However, there are methods available to change the case of the string (uppercase, lowercase, etc.).

The simplest way to capitalize the first letter of a string in Java is by using the String.substring() method:

String str = "hello world!"; // capitalize first letter String output = str.substring(0, 1).toUpperCase() + str.substring(1); // print the string System.out.println(output); // Hello world! 

The above example transforms the first letter of string str to uppercase and leaves the rest of the string the same. If the string is null or empty, the above code throws an exception. However, we can write a functional capitalize() that makes sure the string has at least one character before using the 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 whenever you want to make the first letter of a string uppercase:

System.out.println(capitalize("hello world!")); // Hello world! System.out.println(capitalize("heLLo")); // HeLLo System.out.println(capitalize(null)); // null 

Notice the 2nd line of the above code snippet, only the first letter is capitalized. If you want to ensure only the first letter is in uppercase and the remaining string is lowered case, you can do the following:

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

The Apache Commons Lang library is another way to capitalize the first letter of a string in Java. If you are using Gradle, add the following dependency to your build.gradle file:

implementation 'org.apache.commons:commons-lang3:3.9' 
dependency> groupId>org.apache.commonsgroupId> artifactId>commons-lang3artifactId> version>3.9version> dependency> 

The StringUtils class from Commons Lang provides the capitalize() method to change the first letter to uppercase:

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

Apache Commons Lang offers many extra methods that are not included in standard Java libraries ( java.lang package). It includes String manipulation methods, basic numerical methods, object reflection, concurrency, creation and serialization, and System properties.

In this article, we looked at different ways to capitalize the first letter of a string in Java. The simple approach is to use the String class’s substring() method. However, if you are already using Apache Commons Lang in your project, just use the StringUtils class to capitalize the first letter of a string. Since string capitalization is a common task in all programming languages, I have also written a tutorial to do the same in JavaScript. Take a look at this guide. Read Next: Capitalize the first letter of each word in a string using Java ✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like.

Источник

Capitalize the first letter of each word in a string using Java

In this short guide, you will learn how to capitalize the first letter of each word in a string using Java. We have already learned to capitalize the first letter of a string in Java. But capitalizing each word in a string is a bit tricky.

The easiest way to capitalize the first character of each word of a string is by using Java 8 Stream API:

String str = "welcome to java"; // uppercase first letter of each word String output = Arrays.stream(str.split("\\s+")) .map(t -> t.substring(0, 1).toUpperCase() + t.substring(1)) .collect(Collectors.joining(" ")); // print the string System.out.println(output); // Welcome To Java 

In the above example, we first split the string into an array using the split() method. The array is passed to Arrays.stream() as a parameter that turns it into a Stream object. Afterward, we use the map() method from streams to capitalize each word before converting it back to a string using the collect() method. If the string is empty or null , the above code will throw an exception. Let us write a function capitalizeAll() that makes sure there is no exception while transforming string:

public static String capitalizeAll(String str)  if (str == null || str.isEmpty())  return str; > return Arrays.stream(str.split("\\s+")) .map(t -> t.substring(0, 1).toUpperCase() + t.substring(1)) .collect(Collectors.joining(" ")); > 
System.out.println(capitalizeAll("welcome to java")); // Welcome To Java System.out.println(capitalizeAll("this is awesome")); // This Is Awesome System.out.println(capitalizeAll("mcdonald in lahore")); // Mcdonald In Lahore System.out.println(capitalizeAll(null)); // null 

The above solution only changes the first letter of each word while all other characters remain the same. Sometimes, you want to ensure that only the first character of a word is capitalized. Let us write another function capitalizeFully() for this:

public static String capitalizeFully(String str)  if (str == null || str.isEmpty())  return str; > return Arrays.stream(str.split("\\s+")) .map(t -> t.substring(0, 1).toUpperCase() + t.substring(1).toLowerCase()) .collect(Collectors.joining(" ")); > 

The only difference between capitalizeAll() and capitalizeFully() is that the latter function explicitly changes the remaining part of the word to lowercase:

System.out.println(capitalizeFully("i aM aTTa")); // I Am Atta System.out.println(capitalizeFully("fOo bAr")); // Foo Bar 

If you are using Java 9 or higher, it is possible to use a regular expression with the String.replaceAll() method to capitalize the first letter of each word in a string. The String.replaceAll() method replaces each substring of this string that matches the given regular expression with the given replacement. Here is an example:

public static String capitalizeAll(String str)  if (str == null || str.isEmpty())  return str; > return Pattern.compile("\\b(.)(.*?)\\b") .matcher(str) .replaceAll(match -> match.group(1).toUpperCase() + match.group(2)); > 
System.out.println(capitalizeAll("12 ways to learn java")); // 12 Ways To Learn Java System.out.println(capitalizeAll("i am atta")); // I Am Atta System.out.println(capitalizeAll(null)); // null 

The Apache Commons Text library is yet another option to convert the first character of each word in a string to uppercase. Add the following dependency to your build.gradle file:

implementation 'org.apache.commons:commons-text:1.8' 
dependency> groupId>org.apache.commonsgroupId> artifactId>commons-textartifactId> version>1.8version> dependency> 

Now you can use the capitalize() method from the WordUtils class to capitalize each word in a string:

System.out.println(WordUtils.capitalize("love is everywhere")); // Love Is Everywhere System.out.println(WordUtils.capitalize("sky, sky, blue sky!")); // Sky, Sky, Blue Sky! System.out.println(WordUtils.capitalize(null)); // null 

The good thing about WordUtils methods is that they handle the exceptions gracefully. There won’t be any exception even if the input is null . The WordUtils class also provides the capitalizeFully() method that capitalizes the first character and turns the remaining characters of each word into lowercase:

System.out.println(WordUtils.capitalizeFully("fOO bAR")); // Foo Bar System.out.println(WordUtils.capitalizeFully("sKy is BLUE!")); // Sky Is Blue! 

You might also like.

Источник

How to capitalize first letter in java

Here are the steps to capitalize first letter of each word.

Оцените статью