1. Introduction
Capitalizing the first letter of each word in a string is a common operation in string manipulation and text processing. In Java, this can be achieved by splitting the string into words and then converting the first letter of each word to uppercase. In this tutorial, we will write a Java program to capitalize the first letter of each word in a given string.
2. Program Steps
1. Define a main method to serve as the entry point of the program.
2. Declare and initialize a String whose words we want to capitalize.
3. Split the input string into words using the split method.
4. Loop through each word in the resulting array.
5. For each word, capitalize the first letter and append the remaining letters. Concatenate the modified word to the result string.
6. Print the result string.
3. Code Program
public class CapitalizeFirstLetter {
public static void main(String[] args) {
// Step 2: Declare and initialize a String whose words we want to capitalize
String str = "java programming is fun";
// Step 3: Split the input string into words
String[] words = str.split(" ");
// Declare a String to hold the result
StringBuilder result = new StringBuilder();
// Step 4: Loop through each word in the array
for (String word : words) {
// Step 5: Capitalize the first letter of each word and append the remaining letters
String capitalizedWord = word.substring(0, 1).toUpperCase() + word.substring(1);
result.append(capitalizedWord).append(" ");
}
// Remove the trailing space
result.setLength(result.length() - 1);
// Step 6: Print the result string
System.out.println("Capitalized String: " + result);
}
}
Output:
Capitalized String: Java Programming Is Fun
4. Step By Step Explanation
– Step 1: The main method is defined, acting as the entry point of the program.
– Step 2: A String named str is declared and initialized with the value "java programming is fun".
– Step 3: The input string str is split into words using the split method, resulting in an array of words.
– Step 4: A for-each loop is used to loop through each word in the array.
– Step 5: Inside the loop, the first letter of each word is capitalized, and the remaining letters are appended. The modified word is then concatenated to the result string.
– Step 6: The final capitalized string is printed to the console.
This program efficiently capitalizes the first letter of each word in a given string using string manipulation methods in Java.