Capitalize each word of a String in Kotlin
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.
|
1 2 3 4 5 6 7 |
fun main() { val sentence = "capitalize each word" val str = sentence.split(" ") .joinToString(separator = " ", transform = String::capitalize) println(str) } |
Output:
Capitalize Each Word
The code can be further shortened as:
|
1 2 3 4 5 6 7 8 |
fun main() { val sentence = "capitalize each word" val str = sentence.split(" ") .joinToString(" ") { it.capitalize() } println(str) } |
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:
|
1 2 3 4 5 6 7 8 |
fun main() { val sentence = "capitalize each word" val str = sentence.split("\\s+".toRegex()) .joinToString(" ") { it.capitalize() } println(str) } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import java.util.regex.Pattern fun capitalize(str: String?): String { val sb = StringBuffer() val matcher = Pattern.compile("\\b(\\w)").matcher(str) while (matcher.find()) { matcher.appendReplacement(sb, matcher.group(1).toUpperCase()) } matcher.appendTail(sb) return sb.toString() } fun main() { val sentence = "capitalize each word" val str = capitalize(sentence) println(str) } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
fun capitalize(str: String): String { val words = str.split(" ") val sb = StringBuilder() words.forEach { if (it != "") { sb.append(it[0].toUpperCase()).append(it.substring(1)) } sb.append(" ") } return sb.toString().trim { it <= ' ' } } fun main() { val sentence = "capitalize each word!" val str = capitalize(sentence) println(str) } |
Output:
Capitalize Each Word!
That’s all about capitalizing each word in a given string in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)