The Wayback Machine - https://web.archive.org/web/20240718150939/https://www.geeksforgeeks.org/java-program-to-capitalize-the-first-letter-of-each-word-in-a-string/
Open In App

Java Program to Capitalize the First Letter of Each Word in a String

Last Updated : 07 Feb, 2024
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

In Java Programming, we can be able to capitalize the first letter of each word in the given String value by using toUpperCase(), toLowerCase(), and another one is substring() method. These methods are available String class in Java and these methods are useful for our problem.

In this article, we will learn how to capitalize the first letter of each word in a String in Java using different methods.

Approach to capitalize the first letter of each word in a String

To capitalize the first letter of each word in a String, first, we have taken one String value then take the first character from each word in the given string then print the result.

  • First, we have created one Java class.
  • After that, we created one method that is capitalizeWords() which capitalizes the first letter of each word in a String
  • After that, we called this method in the main method and then gave input to the method already taken String value.
  • Finally, print the result.

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

1. Using split() and substring() methods

Below is the implementation of split() and substring() methods to capitalize the first letter of each word in a String.

Java




// Java Program to capitalize the first letter of each word in a String using split() and substring() methods
import java.util.Arrays;
public class CapitalizeWordsExample {
    public static void main(String[] args) {
        // input string
        String input = "welcome to geeksforgeeks";
  
        // call the capitalizeWords function and store the result
        String result = capitalizeWords(input);
  
        // print the original and modified strings
        System.out.println("Input: " + input);
        System.out.println("Output: " + result);
    }
  
    // function to capitalize the first letter of each word
    public static String capitalizeWords(String input) {
        // split the input string into an array of words
        String[] words = input.split("\\s");
  
        // StringBuilder to store the result
        StringBuilder result = new StringBuilder();
  
        // iterate through each word
        for (String word : words) {
            // capitalize the first letter, append the rest of the word, and add a space
            result.append(Character.toTitleCase(word.charAt(0)))
                  .append(word.substring(1))
                  .append(" ");
        }
  
        // convert StringBuilder to String and trim leading/trailing spaces
        return result.toString().trim();
    }
}


Output

Input welcome to geeksforgeeks
Output Welcome To Geeksforgeeks


Explanation of the Program:

  • In the above program, we have taken one input string value that is welcome to geeksforgeeks.
  • After this we split this String into String array by using split() method.
  • After that we have taken each character from word by using loop from string array.
  • Then change that character from small to capital.
  • Then Append the Result to String builder after that it will print the result.

2. Using Java Streams

Java




// Java Program to capitalize the first letter of each word in a String using Java Streams
import java.util.Arrays;
import java.util.stream.Collectors;
  
public class CapitalizeWordsExample {
    public static void main(String[] args) {
        // input string
        String input = "welcome to geeksforgeeks";
  
        // call the capitalizeWords function and store the result
        String result = capitalizeWords(input);
  
        // print the original and modified strings
        System.out.println("Input: " + input);
        System.out.println("Output: " + result);
    }
  
    // function to capitalize the first letter of each word using Java streams
    public static String capitalizeWords(String input) {
        // split the input string into an array of words, stream the array
        // apply the capitalization transformation and join the words back
        return Arrays.stream(input.split("\\s"))
                     .map(word -> Character.toTitleCase(word.charAt(0)) + word.substring(1))
                     .collect(Collectors.joining(" "));
    }
}


Output

Input: welcome to geeksforgeeks
Output: Welcome To Geeksforgeeks


Explanation of the Program:

  • In the above program, first we have taken a String Value as input.
  • After that converted it into streams by using Array class.
  • Then take the first letter from the word and change into Capital letter then added to the collection.
  • Finally print the result.

3. Using StringBuilder

In this Java code, we have taken one string value, after that we have taken first letter of each word and converted it into capitalize then print the result.

Java




// Java Program to capitalize the first letter of each word in a String using StringBuilder
import java.util.Arrays;
public class CapitalizeWordsExample 
{
    public static String capitalizeWords(String input) 
    {
        if (input == null || input.isEmpty()) 
        {
            return input;
        }
  
        // split the input string into words using whitespace
        String[] words = input.split("\\s");
  
        // create a StringBuilder
        StringBuilder result = new StringBuilder();
  
        for (String word : words) 
        {
            // capitalize the first letter of each word and append the rest of the word
            result.append(Character.toUpperCase(word.charAt(0)))
                  .append(word.substring(1).toLowerCase())
                  .append(" "); // Add a space between words
        }
  
        // remove the trailing space and return the capitalized string
        return result.toString().trim();
    }
  
    public static void main(String[] args) 
    {
      
        String inputString = "welcome to geeksforgeeks";
        String capitalizedString = capitalizeWords(inputString);
  
        System.out.println("Original String: " + inputString);
        System.out.println("Capitalized String: " + capitalizedString);
    }
}


Output

Original String: welcome to geeksforgeeks
Capitalized String: Welcome To Geeksforgeeks


Explanation of the Program:

  • In this above example, first we have taken one string value in main method.
  • After that we have used capitalizeWords().
  • To this method, we have given String value as input.
  • This method can be able to convert capitalize the first letter of each word in a String by using this function.
  • In this user defined function first, we have checked the given string is empty or not, if given String is empty this function returns the empty value as a string.
  • After that we have converted the String into String array by using split method.
  • After that we have created the StringBuilder class object.


Similar Reads

Capitalize the First Letter of a String in Java Using Regex
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 discu
2 min read
Capitalize the First Letter of a String in Java
In Java, to check if a String contains only uppercase letters, we can use many approaches. These approaches verify each character in the String to ensure they are all in uppercase. A simple method, such as iterating through the characters and checking their case. In this article, we will discuss how to check if a String contains only uppercase lett
4 min read
Capitalize the first and last character of each word in a string
Given the string, the task is to capitalise the first and last character of each word in a string.Examples: Input: Geeks for geeks Output: GeekS FoR GeekS Input: Geeksforgeeks is best Output: GeeksforgeekS IS BesT Approach Create a character array of the StringRun a loop from the first letter to the last letter.Check if the character is the startin
6 min read
Get the first letter of each word in a string using regex in Java
Given a string, extract the first letter of each word in it. "Words" are defined as contiguous strings of alphabetic characters i.e. any upper or lower case characters a-z or A-Z. Examples: Input : Geeks for geeks Output :Gfg Input : United Kingdom Output : UK Below is the Regular expression to extract the first letter of each word. It uses '/b'(on
1 min read
Print first letter of each word in a string using regex
Given a string, extract the first letter of each word in it. "Words" are defined as contiguous strings of alphabetic characters i.e. any upper or lower case characters a-z or A-Z. Examples: Input : Geeks for geeksOutput :Gfg Input : United KingdomOutput : UKBelow is the Regular expression to extract the first letter of each word. It uses '/b'(one o
3 min read
Java Program To Find Longest Common Prefix Using Word By Word Matching
Given a set of strings, find the longest common prefix. Examples: Input : {“geeksforgeeks”, “geeks”, “geek”, “geezer”} Output : "gee" Input : {"apple", "ape", "april"} Output : "ap"Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution. We start with an example. Suppose there are two strings- “geeksforgeeks” and “geeks”
5 min read
Extracting each word from a String using Regex in Java
Given a string, extract words from it. "Words" are defined as contiguous strings of alphabetic characters i.e. any upper or lower case characters a-z or A-Z. Examples: Input : Funny?? are not you? Output : Funny are not you Input : Geeks for geeks?? Output : Geeks for geeks We have discussed a solution for C++ in this post : Program to extract word
2 min read
Java program to count the characters in each word in a given sentence
Write a Java program to count the characters in each word in a given sentence? Examples: Input : geeks for geeksOutput :geeks->5for->3geeks->5 Recommended: Please solve it on PRACTICE first, before moving on to the solution. Approach:Here we have to find out number of words in a sentence and the corresponding character count of each word.
3 min read
Print last character of each word in a string
Given string str, the task is to print the last character of each word in the string.Examples: Input: str = "Geeks for Geeks" Output: s r s Input: str = "computer applications" Output: r s Approach: Append a space i.e. " " at the end of the given string so that the last word in the string is also followed by a space just like all the other words in
4 min read
Java Program to find the Last Index of a Particular Word in a String
To find out the last occurrence of a character or string from a given string across which the substring or character is been searched over and returning the index value of the character or substring is found. Real-life Example: Consider an example of a book. The book contains pages where pages contain words. Now if a user wants to figure out the oc
4 min read
Practice Tags :
three90RightbarBannerImg