java tutorial: java uppercase first letter

In the following example, two ways to change the first letter to uppercase will be shared.

Example 1

* Use ASCII table
* The ASCII code of lowercase letters a-z is: 97-122;
    public static String upperCaseFirstLetterV2(String str) {
        if(str == null || str.length() <= 0) {
            return str;
        }
        char[] cs = str.toCharArray();
        if(cs[0] < 97 || cs[0] > 122) {
            return str;
        }
        cs[0] -= 32;
        return String.valueOf(cs);
    }

Example 2

* Use string substring function and toUpperCase function
    public static String upperCaseFirstLetterV1(String str) {
        if(str == null || str.length() <= 0) {
            return str;
        }
        String firstLetter = str.substring(0, 1);
        if(!firstLetter.matches("[a-z]")) {
            return str;
        }
        str = firstLetter.toUpperCase() + str.substring(1);
        return str;
    }

Sample code

public class UpperCase {

    /**
     * Use string substring function and toUpperCase function
     *
     * @param str
     * @return
     */
    public static String upperCaseFirstLetterV1(String str) {
        if(str == null || str.length() <= 0) {
            return str;
        }
        String firstLetter = str.substring(0, 1);
        if(!firstLetter.matches("[a-z]")) {
            return str;
        }
        str = firstLetter.toUpperCase() + str.substring(1);
        return str;
    }

    /**
     * Use ASCII table
     * The ASCII code of lowercase letters a-z is: 97-122;
     *
     * @param str
     * @return
     */
    public static String upperCaseFirstLetterV2(String str) {
        if(str == null || str.length() <= 0) {
            return str;
        }
        char[] cs = str.toCharArray();
        if(cs[0] < 97 || cs[0] > 122) {
            return str;
        }
        cs[0] -= 32;
        return String.valueOf(cs);
    }

    public static void main(String[] args) {
        String str = "hello";
        String s = upperCaseFirstLetterV1(str);
        System.out.println("s = " + s);

        String s1 = upperCaseFirstLetterV2(str);
        System.out.println("s1 = " + s1);
    }
}

Add a Comment

Your email address will not be published.