Java String capitalize

Introduction

Capitalize a String changing the first letter to title case as per Character#toTitleCase(char)}.

No other letters are changed.

A null input String returns null.

capitalize(null)  = null
capitalize("")    = ""
capitalize("cat") = "Cat"
capitalize("cAt") = "CAt"

This solution is using StringBuffer.

public class Main {
    public static void main(String[] argv) throws Exception {
        String str = "demo2s.com";
        System.out.println(capitalize(str));
    }//from w  w  w  .  ja  va2s  . c  o m
    public static String capitalize(String str) {
        int strLen;
        if (str == null || (strLen = str.length()) == 0) {
            return str;
        }
        return new StringBuffer(strLen).append(Character.toTitleCase(str.charAt(0))).append(str.substring(1))
                .toString();
    }
}

Java String capitalize the first character to uppercase by String#toUpperCase()

The returned string will have the same value as the specified string if its first character is non-alphabetic, if its first character is already uppercase, or if the specified string is of length 0.

For example:

capitalize("foo bar").equals("Foo bar");
capitalize("2b or not 2b").equals("2b or not 2b")
capitalize("Foo bar").equals("Foo bar");
capitalize("").equals("");

throws NullPointerException if s is null.

public class Main {
    public static void main(String[] argv) throws Exception {
        String s = "demo2s.com";
        System.out.println(capitalize(s));
    }/*from   w w  w.  j  a v  a2s.c om*/
    public static String capitalize(String s) {
        if (s.length() == 0) {
            return s;
        }
        char first = s.charAt(0);
        char capitalized = Character.toUpperCase(first);
        return (first == capitalized) ? s : capitalized + s.substring(1);
    }

}

//package com.demo2s;

public class Main {
  public static void main(String[] argv) throws Exception {
    String str = "demo2s.com demo";
    System.out.println(capitalizeString(str));
  }/* w w  w . j a  va 2s  .c om*/

  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