Capitalize First Letter of Each Word in Java
Capitalizing the first letter of each word is a common string manipulation task used in formatting names, titles, and sentences.
In this program, we process the string character by character without using built-in string formatting methods.
Understanding the Problem
Given a sentence, we need to:
- Capitalize the first character of the sentence.
- Capitalize any character that follows a space.
- Keep all other characters unchanged.
Example 1
Input: java is fun
Output: Java Is Fun
Example 2
Input: welcome to kodekraftt
Output: Welcome To Kodekraftt
Logic Explanation
- Convert the string into a character array.
- Capitalize the first character if it is lowercase.
- Whenever a space is found, capitalize the next character.
- Append characters to form the final string.
Java Program to Capitalize First Letter of Each Word
import java.util.Scanner;
public class CapitalizeWords {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String str = sc.nextLine();
char[] ch = str.toCharArray();
for (int i = 0; i < ch.length; i++) {
if (i == 0 && ch[i] >= 'a' && ch[i] <= 'z') {
ch[i] = (char)(ch[i] - 32);
}
else if (ch[i] == ' ' && i + 1 < ch.length) {
if (ch[i + 1] >= 'a' && ch[i + 1] <= 'z') {
ch[i + 1] = (char)(ch[i + 1] - 32);
}
}
}
System.out.print("Formatted string: ");
System.out.println(ch);
}
}
Sample Output
Enter a sentence: java is fun
Formatted string: Java Is Fun
Important Notes
- Only lowercase letters are converted.
- Multiple spaces are handled correctly.
- No use of
toUpperCase()orsplit().
Practice Challenges
- Convert the rest of each word to lowercase.
- Capitalize words separated by special characters.
- Ignore extra spaces at the beginning and end.
This program improves understanding of character manipulation and ASCII-based conversions in Java.