This article explores different ways to capitalize each word in a given string in Kotlin.

1. Using String::capitalize

The idea is to split the given string with whitespace as a delimiter to extract each word, capitalize the first character of each word with String::capitalize, and join all words together using the joinToString() function.

Download Code

Output:

Capitalize Each Word

 
The code can be further shortened as:

Download Code

Output:

Capitalize Each Word

 
To replace consecutive whitespace characters with a single space, we can use the \s+ regex to split the string, as shown below:

Download Code

Output:

Capitalize Each Word

2. Using Matcher

Another option is to split the input sequence on matches of a regular expression using the matcher returned by the Pattern.compile() function. This JDK-specific approach can be used as follows to capitalize the first character of each word:

Download Code

Output:

Capitalize Each Word!

3. Custom Routine

We can even write your custom logic to capitalize each word of a String. The idea is to split the given string using space as a delimiter. Then iterate through the returned list of words, capitalize the first character of each word, and append the capitalized string to a String builder with the space. Finally, return the string representation of the String builder.

Download Code

Output:

Capitalize Each Word!

That’s all about capitalizing each word in a given string in Kotlin.