Java 首字母转大写,StringUtils.capitalize

================================

©Copyright 蕃薯耀 2022-09-01

https://www.cnblogs.com/fanshuyao/

 

一、首字母转大写最简单的方法

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
        </dependency>

 

org.apache.commons.lang3.StringUtils.capitalize(String str)

示例:

 StringUtils.capitalize(null)  = null
 StringUtils.capitalize("")    = ""
 StringUtils.capitalize("cat") = "Cat"
 StringUtils.capitalize("cAt") = "CAt"
 StringUtils.capitalize("'cat'") = "'cat'"

 

Java首字母转小写

StringUtils.uncapitalize("")

 

 StringUtils.uncapitalize(null)  = null
 StringUtils.uncapitalize("")    = ""
 StringUtils.uncapitalize("cat") = "cat"
 StringUtils.uncapitalize("Cat") = "cat"
 StringUtils.uncapitalize("CAT") = "cAT"

 

 

二、Java自定义首字母转大写

    public static String firstUpper(String fieldName) {
        if(fieldName == null || fieldName.length() < 1) {
            return fieldName;
        }
        return fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
    }

 

    public static void main(String[] args) {
        System.out.println(firstUpper(null));
        System.out.println(firstUpper(""));
        System.out.println(firstUpper("a"));
        System.out.println(firstUpper("aa"));
        System.out.println(firstUpper("Aa"));
        System.out.println(firstUpper("AAaaa"));
        System.out.println(firstUpper("-aaaaa"));
    }
 
 
结果:
 
null
 
A
Aa
Aa
AAaaa
-aaaaa

 

 

三、Setter和Getter方法

    public static String getSetterName(String fieldName) {
        return "set" + firstUpper(fieldName);
    }
    
    public static String getGetterName(String fieldName) {
        return "get" + firstUpper(fieldName);
    }

 

 

 

 

(时间宝贵,分享不易,捐赠回馈,^_^)

 

================================

©Copyright 蕃薯耀 2022-09-01

https://www.cnblogs.com/fanshuyao/

 

posted @ 2022-09-01 14:14  蕃薯耀  阅读(942)  评论(1编辑  收藏  举报