Java Data Type How to - Capitalize First Char of Each Word in a String








Question

We would like to know how to capitalize First Char of Each Word in a String.

Answer

public class Main {
  public static void main(String[] args) {
    String FinalStringIs = "";
    String testNames = "this is a test";
    String[] name = testNames.split("\\s");
/*  ww w .j  a v a 2s. c o  m*/
    for (String nameIs : name) {
      FinalStringIs += getIntiCapString(nameIs) + ",";
    }
    System.out.println("Final Result " + FinalStringIs);

  }

  public static String getIntiCapString(String param) {
    if (param != null && param.length() > 0) {
      char[] charArray = param.toCharArray();
      charArray[0] = Character.toUpperCase(charArray[0]);
      return new String(charArray);
    } else {
      return "";
    }
  }
}