How to capitalize the first letter of each word in a string with Java

3 Answers

0 votes
public class Program {
     public static String CapitalizeFirstLetters(String s) {
        String[] words = s.split(" ");
        StringBuilder sb = new StringBuilder();
         
        for (int i = 0; i < words.length; i++) {
            sb.append(Character.toUpperCase(words[i].charAt(0)));
            sb.append(words[i].substring(1));
         
            if (i < words.length - 1) {
                sb.append(' ');
            }
        }
        
        return sb.toString();
    }
    public static void main(String[] args) {
        String s = "java programming language"; 
         
        s = CapitalizeFirstLetters(s);
         
        System.out.println(s);
    }
   
}


 
/*
run:

Java Programming Language

*/

 



answered Jan 26, 2017 by avibootz
edited May 16, 2024 by avibootz
0 votes
public class MyClass {
    public static String capitalize_each_word_first_letter_of_string(String s) {
        String[] words = s.split(" ");
        String result = "";
 
        for (String word: words) {
            result += Character.toUpperCase(word.charAt(0)) + word.substring(1) + " ";
        }
         
        return result;
    }  
    public static void main(String args[]) {
        String s = "java c php python c++";
          
        s = capitalize_each_word_first_letter_of_string(s);
 
        System.out.println(s);
    }
}
  
  
  
/*
run:
  
Java C Php Python C++ 
 
*/

 



answered May 16, 2024 by avibootz
0 votes
public class MyClass {
    public static String capitalize_each_word_first_letter_of_string(String s) {
        String[] words = s.split(" ");
        StringBuilder sb = new StringBuilder();
         
        for (String word : words) {
            sb.append(word.substring(0, 1).toUpperCase());
            sb.append(word.substring(1).toLowerCase());
            sb.append(" ");
        }
         
        return sb.toString().trim();
    }  
    public static void main(String args[]) {
        String s = "java c php python c++";
           
        s = capitalize_each_word_first_letter_of_string(s);
  
        System.out.println(s);
    }
}
   
   
   
/*
run:
   
Java C Php Python C++
  
*/

 

 



answered May 16, 2024 by avibootz

Related questions

...