Java String Capitalize capitalize(String s)

Here you can find the source of capitalize(String s)

Description

Capitalize a string using java bean conventions.

License

Academic Free License

Declaration

public static String capitalize(String s) 

Method Source Code

//package com.java2s;
// Licensed under the Academic Free License version 3.0

public class Main {
    /**//  w w w. j av a  2 s  .  c om
     * Capitalize a string using java bean
     * conventions.  For instance "fooBar" becomes
     * "FooBar", for use such as "getFooBar".
     */
    public static String capitalize(String s) {
        char[] c = s.toCharArray();
        c[0] = toUpperCase(c[0]);
        return new String(c);
    }

    /**
     * Do an ASCII only upper case conversion.  Case conversion
     * with Locale can result in unexpected side effects.
     */
    public static char toUpperCase(char c) {
        if ('a' <= c && c <= 'z')
            return (char) (c & ~0x20);
        else
            return c;
    }

    /**
     * Do an ASCII only upper case conversion.  Case conversion
     * with Locale can result in unexpected side effects.
     */
    public static String toUpperCase(String s) {
        // first scan to see if string isn't already ok
        int len = s.length();
        int first = -1;
        for (int i = 0; i < len; ++i) {
            char a = s.charAt(i);
            char b = toUpperCase(a);
            if (a != b) {
                first = i;
                break;
            }
        }
        if (first == -1)
            return s;

        // allocate new char buf and copy up to first change
        char[] buf = new char[len];
        s.getChars(0, first, buf, 0);

        // change remainder of string
        for (int i = first; i < len; ++i)
            buf[i] = toUpperCase(s.charAt(i));

        return new String(buf);
    }
}

Related

  1. capitalize(String s)
  2. capitalize(String s)
  3. capitalize(String s)
  4. capitalize(String s)
  5. capitalize(String s)
  6. capitalize(String s)
  7. capitalize(String s)
  8. capitalize(String s)
  9. capitalize(String s)