Sunday, January 26, 2014

How to capitalize the first char of each word in a String?

Source:
import java.util.Arrays;

public class UpperCaseWords {
   public static void main(String[] args) {

      String str1 = "is this is a string with lower case letters?";
      String str2 = "";

      String[] words = str1.split("\\s");

      for(int i=0; i < words.length; i++) {
         char first = Character.toUpperCase(words[i].charAt(0));
         words[i] = first + words[i].substring(1);

         str2 = str2 + words[i];
         // no spaces at end of string
         if (i < words.length ) {
            str2 = str2 + " ";
         }
      }

      System.out.println(str1);
      System.out.println(str2);
   }
}

Output:
   $ java UpperCaseWords 
   is this is a string with lower case letters?
   Is This Is A String With Lower Case Letters? 

Blog Archive