Introduction
Capitalizing the first letter of each word in a string is a common task in text processing. This can be useful for formatting names, titles, or any other text where proper capitalization is required. In Java, there are several ways to achieve this, using both built-in methods and external libraries. This blog post will explore different methods of capitalizing the first letter of each word in Java.
Table of Contents
- Using a Loop and
StringBuilder
- Using
String.split()
andString.join()
- Using Streams (Java 8+)
- Using Apache Commons Lang
WordUtils
- Complete Example Program
- Conclusion
1. Using a Loop and StringBuilder
One of the most straightforward methods to capitalize the first letter of each word is by using a loop to iterate through the words and a StringBuilder
to build the result.
Example:
public class CapitalizeFirstLetterUsingLoop {
public static void main(String[] args) {
String str = "hello world from java";
// Capitalize first letter of each word using a loop and StringBuilder
StringBuilder capitalizedStr = new StringBuilder();
boolean capitalizeNext = true;
for (char c : str.toCharArray()) {
if (Character.isWhitespace(c)) {
capitalizeNext = true;
} else if (capitalizeNext) {
c = Character.toTitleCase(c);
capitalizeNext = false;
}
capitalizedStr.append(c);
}
System.out.println("Original String: " + str);
System.out.println("Capitalized String: " + capitalizedStr.toString());
}
}
Output:
Original String: hello world from java
Capitalized String: Hello World From Java
Explanation:
- A loop is used to iterate through each character in the string.
- The
capitalizeNext
flag is used to determine when to capitalize a character. Character.toTitleCase(c)
is used to capitalize the first letter of each word.
2. Using String.split() and String.join()
Another approach is to split the string into words, capitalize each word, and then join them back together.
Example:
public class CapitalizeFirstLetterUsingSplitJoin {
public static void main(String[] args) {
String str = "hello world from java";
// Capitalize first letter of each word using split() and join()
String[] words = str.split("\\s+");
StringBuilder capitalizedStr = new StringBuilder();
for (String word : words) {
if (word.length() > 0) {
capitalizedStr.append(Character.toUpperCase(word.charAt(0)))
.append(word.substring(1).toLowerCase())
.append(" ");
}
}
// Remove the trailing space
String result = capitalizedStr.toString().trim();
System.out.println("Original String: " + str);
System.out.println("Capitalized String: " + result);
}
}
Output:
Original String: hello world from java
Capitalized String: Hello World From Java
Explanation:
- The string is split into words using
split("\\s+")
. - Each word is capitalized by converting the first letter to uppercase and the rest to lowercase.
- The words are joined back together with spaces.
3. Using Streams (Java 8+)
The Stream API introduced in Java 8 provides a concise way to capitalize the first letter of each word.
Example:
import java.util.Arrays;
import java.util.stream.Collectors;
public class CapitalizeFirstLetterUsingStreams {
public static void main(String[] args) {
String str = "hello world from java";
// Capitalize first letter of each word using streams
String capitalizedStr = Arrays.stream(str.split("\\s+"))
.map(word -> word.isEmpty() ? word :
Character.toUpperCase(word.charAt(0)) + word.substring(1).toLowerCase())
.collect(Collectors.joining(" "));
System.out.println("Original String: " + str);
System.out.println("Capitalized String: " + capitalizedStr);
}
}
Output:
Original String: hello world from java
Capitalized String: Hello World From Java
Explanation:
- The string is split into words using
split("\\s+")
. - The
map
function is used to capitalize the first letter of each word. - The words are joined back together with spaces using
Collectors.joining(" ")
.
4. Using Apache Commons Lang WordUtils
The Apache Commons Lang library provides a utility class WordUtils
that can be used to capitalize the first letter of each word.
Maven Dependency:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
Example:
import org.apache.commons.lang3.text.WordUtils;
public class CapitalizeFirstLetterUsingWordUtils {
public static void main(String[] args) {
String str = "hello world from java";
// Capitalize first letter of each word using WordUtils
String capitalizedStr = WordUtils.capitalizeFully(str);
System.out.println("Original String: " + str);
System.out.println("Capitalized String: " + capitalizedStr);
}
}
Output:
Original String: hello world from java
Capitalized String: Hello World From Java
Explanation:
WordUtils.capitalizeFully(str)
is used to capitalize the first letter of each word.
5. Complete Example Program
Here is a complete program that demonstrates all the methods discussed above to capitalize the first letter of each word in Java.
Example Code:
import org.apache.commons.lang3.text.WordUtils;
import java.util.Arrays;
import java.util.stream.Collectors;
public class CapitalizeFirstLetterExample {
public static void main(String[] args) {
String str = "hello world from java";
// Using Loop and StringBuilder
StringBuilder capitalizedStr1 = new StringBuilder();
boolean capitalizeNext = true;
for (char c : str.toCharArray()) {
if (Character.isWhitespace(c)) {
capitalizeNext = true;
} else if (capitalizeNext) {
c = Character.toTitleCase(c);
capitalizeNext = false;
}
capitalizedStr1.append(c);
}
System.out.println("Using Loop and StringBuilder: " + capitalizedStr1.toString());
// Using split() and join()
String[] words = str.split("\\s+");
StringBuilder capitalizedStr2 = new StringBuilder();
for (String word : words) {
if (word.length() > 0) {
capitalizedStr2.append(Character.toUpperCase(word.charAt(0)))
.append(word.substring(1).toLowerCase())
.append(" ");
}
}
String result2 = capitalizedStr2.toString().trim();
System.out.println("Using split() and join(): " + result2);
// Using Streams
String capitalizedStr3 = Arrays.stream(str.split("\\s+"))
.map(word -> word.isEmpty() ? word :
Character.toUpperCase(word.charAt(0)) + word.substring(1).toLowerCase())
.collect(Collectors.joining(" "));
System.out.println("Using Streams: " + capitalizedStr3);
// Using WordUtils
String capitalizedStr4 = WordUtils.capitalizeFully(str);
System.out.println("Using WordUtils: " + capitalizedStr4);
}
}
Output:
Using Loop and StringBuilder: Hello World From Java
Using split() and join(): Hello World From Java
Using Streams: Hello World From Java
Using WordUtils: Hello World From Java
6. Conclusion
Capitalizing the first letter of each word in a string can be accomplished in several ways in Java. Using a loop and StringBuilder
is straightforward and efficient. The split()
and join()
method provides a clear approach, while streams offer a concise and functional style. The Apache Commons Lang WordUtils
class provides a convenient utility method. By understanding these different methods, you can choose the one that best fits your needs and coding style.
Happy coding!
Comments
Post a Comment
Leave Comment