Java program to capitalize the first character of each word in a string
Here's an example Java program to capitalize the first character of each word in a string:
refer toditfigi:ea.compublic class CapitalizeFirstLetter { public static void main(String[] args) { String input = "this is a string to capitalize"; String[] words = input.split(" "); StringBuilder capitalized = new StringBuilder(); for (String word : words) { String first = word.substring(0, 1); String rest = word.substring(1); capitalized.append(first.toUpperCase() + rest + " "); } String output = capitalized.toString().trim(); System.out.println(output); } }
This program takes an input string, splits it into individual words using the split() method with a space delimiter, and then uses a loop to capitalize the first letter of each word. The StringBuilder class is used to build the capitalized string, and the trim() method is used to remove any leading or trailing whitespace.
For example, if the input string is "this is a string to capitalize", the program will output:
This Is A String To Capitalize
Note that this program only capitalizes the first letter of each word, and does not change the case of any other letters.