public class CapitalizeWords {
public static void main(String[] args) {
String str = "the quick brown fox jumps over the lazy dog";
// Split the string into words using space as the delimiter
String[] words = str.split("\\s");
StringBuilder sb = new StringBuilder();
// Iterate through each word and capitalize the first character
for (String word : words) {
sb.append(Character.toUpperCase(word.charAt(0))).append(word.substring(1)).append(" ");
}
String capitalizedStr = sb.toString().trim();
System.out.println(capitalizedStr);
}
}
The Quick Brown Fox Jumps Over The Lazy Dog
str
and initialize it with the string "the quick brown fox jumps over the lazy dog". We then split the string into words using the split()
method with a regular expression that matches whitespace characters (\\s
) as the delimiter. We create a StringBuilder
object sb
to build the capitalized string.for
loop to iterate through each word in the words
array. Inside the loop, we use the toUpperCase()
method of the Character
class to capitalize the first character of the current word, and we append the rest of the word using the substring()
method. We also append a space character after each word.StringBuilder
object to a string using the toString()
method, and we remove any trailing whitespace using the trim()
method. We then print the capitalized string to the console.