Java String capitalize all words in a string

Description

Java String capitalize all words in a string

//package com.demo2s;

public class Main {
  public static void main(String[] argv) throws Exception {
    String str = "css html java javascript";
    System.out.println(capitaliseAllWords(str));
  }//w w  w .  ja  va 2s .com

  public static String capitaliseAllWords(String str) {
    return capitalizeString(str);
  }

  public static String capitalizeString(String str) {
    int strLen;
    if (str == null || (strLen = str.length()) == 0) {
      return str;
    }
    StringBuffer buffer = new StringBuffer(strLen);
    boolean whitespace = true;
    for (int i = 0; i < strLen; i++) {
      char ch = str.charAt(i);
      if (Character.isWhitespace(ch)) {
        buffer.append(ch);
        whitespace = true;
      } else if (whitespace) {
        buffer.append(Character.toTitleCase(ch));
        whitespace = false;
      } else {
        buffer.append(ch);
      }
    }
    return buffer.toString();
  }

}



PreviousNext

Related