Convert the given string into Capitalized Each Word in Java


This Java program capitalizes the first letter of each word in a given string.

  • The program starts by initializing a StringBuilder object a with the string "tuTor joes coMputer education", and it is printed using System.out.println("Original String : "+a).
  • The first character of the string is checked to see if it is lowercase (its ASCII value is between 97 and 122). If it is, it is converted to uppercase by subtracting 32 from its ASCII value and then setting the new character using the setCharAt() method of the StringBuilder object.
  • Then, a for loop is used to iterate through the remaining characters of the string. If a space character is found (a.charAt(i) == 32), the next character is checked to see if it is lowercase. If it is, it is converted to uppercase and set using the setCharAt() method. Otherwise, if the current character is already uppercase (its ASCII value is between 65 and 90), it is converted to lowercase by adding 32 to its ASCII value and setting the new character using the setCharAt() method.
  • Finally, the updated string is printed using System.out.println("Capitalized Each Word String : "+a).

Source Code

public class Capitalized {
    public static void main(String args[]) {
        //Program to convert the given string into Capitalized Each Word.
        StringBuilder a = new StringBuilder("tuTor joes coMputer education");
        System.out.println("Original String : "+a);
 
        if (a.charAt(0) >= 97 && a.charAt(0) <= 122) {
            int c = (int) a.charAt(0) - 32;
            a.setCharAt(0, (char) c);
        }
        for (int i = 1; i < a.length(); i++) {
 
            if (a.charAt(i) == 32) {
                i++;
                if (a.charAt(i) >= 97 && a.charAt(i) <= 122) {
                    int c = (int) a.charAt(i) - 32;
                    a.setCharAt(i, (char) c);
                }
            }else {
                if (a.charAt(i) >= 65 && a.charAt(i) <= 90) {
                    int c = (int) a.charAt(i) + 32;
                    a.setCharAt(i, (char) c);
                }
            }
        }
 
        System.out.println("Capitalized Each Word String : "+a);
 
    }
}
 

Output

Original String : tuTor joes coMputer education
Capitalized Each Word String : Tutor Joes Computer Education
To download raw file Click Here

Basic Programs