Open In App

Capitalize the First Letter of a String in Java Using Regex

Last Updated : 02 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In Java, we can use regular expressions to make the first character of each word in Uppercase as the word is represented as a String and string is the collection of characters. So, in Java, we can use pattern and matcher class methods to find the first character of a word and then replace it with its uppercase letter.

In this article, we will discuss how to make the first character of each word in Uppercase using regex.

Example of Converting the first character of each word in Uppercase

Input: geeks for geeks
Output: Geeks For Geeks

Input: hello world
Output: Hello World

Program to Make the First Character of Each Word in Uppercase Using Regex

Below is the Regular Expression to make the first character of each word in Uppercase.

Java




// Java Program to make the first character of each word in Uppercase using regex 
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
  
class GFG {
    public static void main(String[] args)
    {
        // given input string
        String s1 = "geeks for geeks";
  
        // regular expression for finding the first letter
        // of string
        Pattern pat = Pattern.compile("\\b\\w");
        Matcher Match = pat.matcher(s1);
  
        StringBuilder answer = new StringBuilder();
  
        // replace the first character with it's uppercase
        while (Match.find()) {
            Match.appendReplacement(
                answer, Match.group().toUpperCase());
        }
        Match.appendTail(answer);
  
        // print the output on the console
        System.out.println("" + answer);
    }
}


Output

Geeks For Geeks




Explanation:

  • In the above program, it converted the first character of each word to uppercase in a given input string using regex.
  • It uses a regular expression (\\b\\w) to identify the first letter of each word.
  • The program then iterates through the matches, replacing each first letter with its uppercase equivalent.
  • Finally, it prints the modified string.
  • In simple, it transforms a sentence so that the first letter of each word is in uppercase.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads