Capitalize First Character Of Each Word In A String In Java

In this post, we will see how to capitalize first character of each word in a given text.


 

1. Naive

Naive solution would be to split the given text using space as a delimiter. Then we iterate through the words array and capitalize first character of each word and append it to a StringBuilder along with space. Finally, return the string representation of the StringBuilder.

 

Download   Run Code

Output:

Techie Delight Is Awesome!

 

2. WordUtils from Apache Commons

Simplest solution would be to use WordUtils class from Apache Commons Lang. It already provides capitalize() method that serves the same purpose.

 

Download

Output:

Techie Delight Is Awesome!

 

3. Java 8

In Java 8, we can get Stream of the words in the given text, capitalize first character of each word and collect it using Collectors.

1. Using Pattern.splitAsStream() to get Stream

 

Download   Run Code

Output:

Techie Delight Is Awesome!

 

2. Using Stream.of() to get Stream

 

Download   Run Code

Output:

Techie Delight Is Awesome!

 

4. Guava

We can also use Joiner class from Guava, along with Splitter and Iterables class, as demonstrated below:

 

Download   Run Code

Output:

Techie Delight Is Awesome!

 

5. Regex

We can also take help of regular expressions in Java to capitalize first character of each word as shown below:

 

Download   Run Code

Output:

Techie Delight Is Awesome!

 
Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of