A string uppercase first letter of transfer (English)

Work met a demand, from propertiesthe first letter of the field to obtain the configuration file, and then get the field to uppercase.
There are two ways to achieve this:

  • 1, using the methods of the String and Character itself provide to fulfill:
    /**
     * 首字母转大写
     * @param s
     * @return
     */
    public static String toUpperFirstOne(String s) {
        if (Character.isUpperCase(s.charAt(0))) {
            return s;
        } else {
            return (new StringBuilder())
                    .append(Character.toUpperCase(s.charAt(0)))
                    .append(s.substring(1))
                    .toString();
        }
    }
  • 2, using the ASCII code features to achieve:
 /**
     * 将字符串的首字母转大写
     * @param s
     * @return
     */
    private static String toUpperFirstCharacter(String s) {
        // 利用ascii编码的前移,效率要高于截取字符串进行转换的操作
        char[] cs = s.toCharArray();
        if (Character.isLowerCase(cs[0])) {
            cs[0] -= 32;
            return String.valueOf(cs);
        }
        return s;
    }

The above two methods can achieve a string of capitalized first letter of the operation switch, after several tests, the second method is slightly better than that in most cases the first efficiency, the time difference between the two is about microsecond and nanosecond level.

PS: The above code, also two methods can be written in lower case corresponding to the first letter of a string into

  • 1, using the methods of the String and Character itself provide to fulfill:
   /**
     * 首字母转小写
     * @param s
     * @return
     */
    public static String toLowerFirstOne(String s) {
        if (Character.isLowerCase(s.charAt(0))) {
            return s;
        } else {
            return (new StringBuilder())
                    .append(Character.toLowerCase(s.charAt(0)))
                    .append(s.substring(1))
                    .toString();
        }
    }
  • 2, using the ASCII code features to achieve
 /**
     * 将字符串的首字母转小写
     * @param s
     * @return
     */
    private static String toLowerFirstCharacter(String s) {
        char[] cs = s.toCharArray();
        if (Character.isUpperCase(cs[0])) {
            cs[0] += 32;
            return String.valueOf(cs);
        }
        return s;
    }

Guess you like

Origin blog.csdn.net/weixin_44290425/article/details/89713866
Recommended