Problem
Given a string, the task is to capitalize the first character of each word in the string. A word is defined as a sequence of non-space characters. The function should return the resulting string with each word’s first character capitalized.
Examples
Example 1:
Input: "hello world"
Output: "Hello World"
Explanation: The first characters of both words 'hello' and 'world' are capitalized.
Example 2:
Input: "java is fun"
Output: "Java Is Fun"
Explanation: The first characters of the words 'java', 'is', and 'fun' are capitalized.
Example 3:
Input: "k5kc is awesome!"
Output: "K5kc Is Awesome!"
Solution
Method 1 - Splitting around spaces and combining
A simple approach involves splitting the text by spaces to get an array of words. We then capitalize the first character of each word and append it, followed by a space, to a StringBuilder. Lastly, we convert the StringBuilder to a string and return it.
Code
Java
// Java program to capitalize first character of each word in a String
class Solution {
public String capitalize(String str) {
String[] words = str.split("\\s");
StringBuilder sb = new StringBuilder();
for (String word: words) {
if (!word.isEmpty()) {
sb.append(Character.toUpperCase(word.charAt(0)));
sb.append(word.substring(1));
}
sb.append(" ");
}
// trim() to remove extra space in the end before returning
return sb.toString().trim();
}
public static void main(String[] args)
{
String sentence = "k5kc is awesome!";
String str = capitalize(sentence);
System.out.println(str);
}
}
Using Java Stream while splitting
In Java 8, we can convert the text into a stream of words, capitalize the first letter of each word, and then collect the results using Collectors.
class Solution {
// Method to capitalize first character of each word in the given text
public String capitalizeFirstChar(String sentence) {
return Pattern.compile("\\s")
.splitAsStream(sentence)
.map(this::capitalize)
.collect(Collectors.joining(" "));
}
// Helper method to capitalize the first character of a word
public String capitalize(String s) {
if (s.equals(""))
return s;
return s.substring(0, 1).toUpperCase() + s.substring(1);
}
}
Using Stream.of() to Get Stream
class Solution {
// Method to capitalize first character of each word in the given text
public String capitalizeFirstChar(String sentence) {
return Stream.of(sentence.split("\\s"))
.map(this::capitalize)
.collect(Collectors.joining(" "));
}
// Helper method to capitalize the first character of a word
public String capitalize(String s) {
if (s.equals(""))
return s;
return s.substring(0, 1).toUpperCase() + s.substring(1);
}
}
Using Libraries
Using Apache commons
The easiest approach is to use the WordUtils
class from Apache Commons Lang, which includes a capitalize()
method for this purpose.
import org.apache.commons.lang3.text.WordUtils;
class Solution {
public static void main(String[] args) {
String sentence = "k5kc is awesome!";
String str = WordUtils.capitalize(sentence);
System.out.println(str);
}
}
Using Guava’s Joiner class
We can also use Joiner class from Guava, along with Splitter and Iterables class, as demonstrated below:
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.Iterables;
class Solution {
// Method to capitalize first character of each word in the given text
public String capitalizeFirstChar(String sentence) {
return Joiner.on(' ')
.join(Iterables.transform(Splitter.on(' ').split(sentence),
this::capitalize));
}
// Helper method to capitalize the first character of a word
public String capitalize(String s) {
if (s.equals(""))
return s;
return s.substring(0, 1).toUpperCase() + s.substring(1);
}
}
Python
class Solution:
def capitalizeFirstChar(self, text: str) -> str:
words = text.split()
capitalized_words = [word.capitalize() for word in words]
return ' '.join(capitalized_words)
Method 2 - Using Regex
We can also use regular expressions to capitalize the first letter of each word, as demonstrated below:
Code
Java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Solution {
// Method to capitalize the first character of each word in the given text
public String capitalizeFirstChar(String str) {
StringBuffer sb = new StringBuffer();
Matcher matcher = Pattern.compile("\\b(\\w)").matcher(str);
while (matcher.find()) {
matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
}
matcher.appendTail(sb);
return sb.toString();
}
}
Python
import re
class Solution:
# Method to capitalize the first character of each word in the given text
def capitalizeFirstChar(self, text: str) -> str:
return re.sub(r'\b\w', lambda x: x.group().upper(), text)