Java - How to capitalize the first letter of each word in a String

In this section, we will show you four different ways to capitalize the first letter of each word in a String using Java.

Following ways can be used to capitalize the first letter of each word in a String in Java:

  1. By using Java 8 Stream
  2. By using StringTokenizer
  3. By using Pattern.compile() and replaceAll method
  4. By using Apache Commons Text

Example 1: Using Java 8 Stream

First split the string into an array using the split() method. Then array is passed to Arrays.stream() as a parameter that turns it into a Stream object. Then, we use the map() method from streams to capitalize each word and finally collect all words again and join them into one sentence.

import java.util.Arrays;
import java.util.stream.Collectors;

public class Main {

// Driver code
public static void main(String[] args)
{
String str = "how are you";
System.out.println("Input => " + str);
String result = capitalize(str);
System.out.println("Output => "+result);
}

public static String capitalize(String string) {

if (string == null || string.isEmpty()) {
return "Empty String";
}

return Arrays.stream(string.split("\\s+"))
.map(str -> str.substring(0, 1).
toUpperCase() + str.substring(1))
.collect(Collectors.joining(" "));
}
}


Console Output:
Input => how are you
Output => How Are You


Assure that only the first character of a word is uppercase, and remaining characters of each word is lowercase:

import java.util.Arrays;
import java.util.stream.Collectors;

public class Main {

// Driver code
public static void main(String[] args)
{
String str = "hoW are yOU";
System.out.println("Input => " + str);
String result = capitalizeFully(str);
System.out.println("Output => "+result);
}

public static String capitalizeFully(String string) {

if (string == null || string.isEmpty()) {
return "Empty String";
}

return Arrays.stream(string.split("\\s+")).
map(str -> str.substring(0, 1).toUpperCase() +
str.substring(1).toLowerCase()).
collect(Collectors.joining(" "));
}
}


Console Output:
Input => hoW are yOU
Output => How Are You


Example 2: Using StringTokenizer

StringTokenizer breaks the sentence into words. Then just iterate over each word and replace the first letter with an uppercase one.

import java.util.StringTokenizer;

public class Main {

// Driver code
public static void main(String[] args)
{
String str = "how are you";
System.out.println("Input => " + str);
String result = capitalize(str);
System.out.println("Output => "+result);

System.out.println();

String str1 = "java is very easy to learn";
System.out.println("Input => " + str1);
String result1 = capitalize(str1);
System.out.println("Output => "+result1);
}

public static String capitalize(String string) {

if (string == null || string.isEmpty()) {
return "Empty String";
}

StringTokenizer tokens = new StringTokenizer(string);
while (tokens.hasMoreElements()) {
String token = (String) tokens.nextElement();
string = string.replaceAll(token, token.
substring(0, 1).toUpperCase() +
token.substring(1));
}
return string;
}
}


Console Output:
Input => how are you
Output => How Are You

Input => java is very easy to learn
Output => Java Is Very Easy To Learn


Assure that only the first character of a word is uppercase, and remaining characters of each word is lowercase:

import java.util.StringTokenizer;

public class Main {

// Driver code
public static void main(String[] args)
{
String str = "hoW aRe yOU";
System.out.println("Input => " + str);
String result = capitalizeAll(str);
System.out.println("Output => "+result);

System.out.println();

String str1 = "jaVa iS vERy eaSY tO leArn";
System.out.println("Input => " + str1);
String result1 = capitalizeAll(str1);
System.out.println("Output => "+result1);
}

public static String capitalizeAll(String string) {

if (string == null || string.isEmpty()) {
return "Empty String";
}

StringTokenizer tokens = new StringTokenizer(string);
while (tokens.hasMoreElements()) {
String token = (String) tokens.nextElement();
string = string.replaceAll(token, token.
substring(0, 1).toUpperCase() +
token.substring(1).toLowerCase());
}
return string;
}
}


Console Output:
Input => hoW aRe yOU
Output => How Are You

Input => jaVa iS vERy eaSY tO leArn
Output => Java Is Very Easy To Learn


Example 3: Using Pattern.compile() and replaceAll method

If you are utilizing Java 9 or higher, it is possible to utilize a conventional expression with the String.replaceAll() method to capitalize the first letter of each word in a string. Pattern.compile() consumes a regular expression. The matcher() consumes the parameter that will be held against the Pattern. After that we supersede the first letter for each matching word again.

import java.util.regex.Pattern;

public class Main {

// Driver code
public static void main(String[] args)
{
String str = "how are you";
System.out.println("Input => " + str);
String result = capitalize(str);
System.out.println("Output => "+result);

System.out.println();

String str1 = "java is very easy to learn";
System.out.println("Input => " + str1);
String result1 = capitalize(str1);
System.out.println("Output => "+result1);
}

public static String capitalize(String string) {

if (string == null || string.isEmpty()) {
return "Empty String";
}

return Pattern.compile("\\b(.)(.*?)\\b")
.matcher(string)
.replaceAll(match -> match.group(1).
toUpperCase() + match.group(2));
}
}


Console Output:
Input => how are you
Output => How Are You

Input => java is very easy to learn
Output => Java Is Very Easy To Learn


Assure that only the first character of a word is uppercase, and remaining characters of each word is lowercase:

import java.util.regex.Pattern;

public class Main {

// Driver code
public static void main(String[] args)
{
String str = "hoW aRe yOU";
System.out.println("Input => " + str);
String result = capitalizeAll(str);
System.out.println("Output => "+result);

System.out.println();

String str1 = "jaVa iS vERy eaSY tO leArn";
System.out.println("Input => " + str1);
String result1 = capitalizeAll(str1);
System.out.println("Output => "+result1);
}

public static String capitalizeAll(String string) {

if (string == null || string.isEmpty()) {
return "Empty String";
}

return Pattern.compile("\\b(.)(.*?)\\b")
.matcher(string)
.replaceAll(match -> match.group(1).
toUpperCase() + match.group(2).toLowerCase());
}
}


Console Output:
Input => hoW aRe yOU
Output => How Are You

Input => jaVa iS vERy eaSY tO leArn
Output => Java Is Very Easy To Learn


Example 4: Using Apache Commons Text

Download Apache Commons Text

<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>1.10.0</version>
</dependency>

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

import org.apache.commons.text.WordUtils;

public class Main {

// Driver code
public static void main(String[] args)
{
String str = "how are you";
System.out.println("Input => " + str);
String result = WordUtils.capitalize(str);
System.out.println("Output => "+result);

System.out.println();

String str1 = "java is very easy to learn";
System.out.println("Input => " + str1);
String result1 = WordUtils.capitalize(str1);
System.out.println("Output => "+result1);
}
}

 

Console Output:
Input => how are you
Output => How Are You

Input => java is very easy to learn
Output => Java Is Very Easy To Learn


Assure that only the first character of a word is uppercase, and remaining characters of each word is lowercase:

The WordUtils class also provides the capitalizeFully() method that capitalizes the first character and turns the remaining characters of each word into lowercase:

import org.apache.commons.text.WordUtils;

public class Main {

// Driver code
public static void main(String[] args)
{
String str = "hoW aRe yOU";
System.out.println("Input => " + str);
String result = WordUtils.capitalizeFully(str);
System.out.println("Output => "+result);

System.out.println();

String str1 = "jaVa iS vERy eaSY tO leArn";
System.out.println("Input => " + str1);
String result1 = WordUtils.capitalizeFully(str1);
System.out.println("Output => "+result1);
}
}


Console Output:
Input => hoW aRe yOU
Output => How Are You

Input => jaVa iS vERy eaSY tO leArn
Output => Java Is Very Easy To Learn

More related topics,

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete