zoukankan      html  css  js  c++  java
  • java中驼峰与下横线格式字符串互转算法

    public static final char UNDERLINE = '_';
    
        /**
         * 驼峰格式字符串转换为下划线格式字符串
         * 
         * @param param
         * @return
         */
        public static String camelToUnderline(String param) {
            if (param == null || "".equals(param.trim())) {
                return "";
            }
            int len = param.length();
            StringBuilder sb = new StringBuilder(len);
            for (int i = 0; i < len; i++) {
                char c = param.charAt(i);
                if (Character.isUpperCase(c)) {
                    sb.append(UNDERLINE);
                    sb.append(Character.toLowerCase(c));
                } else {
                    sb.append(c);
                }
            }
            return sb.toString();
        }
    
        /**
         * 下划线格式字符串转换为驼峰格式字符串
         * 
         * @param param
         * @return
         */
        public static String underlineToCamel(String param) {
            if (param == null || "".equals(param.trim())) {
                return "";
            }
            int len = param.length();
            StringBuilder sb = new StringBuilder(len);
            for (int i = 0; i < len; i++) {
                char c = param.charAt(i);
                if (c == UNDERLINE) {
                    if (++i < len) {
                        sb.append(Character.toUpperCase(param.charAt(i)));
                    }
                } else {
                    sb.append(c);
                }
            }
            return sb.toString();
        }
    
        /**
         * 下划线格式字符串转换为驼峰格式字符串2
         * 
         * @param param
         * @return
         */
        public static String underlineToCamel2(String param) {
            if (param == null || "".equals(param.trim())) {
                return "";
            }
            StringBuilder sb = new StringBuilder(param);
            Matcher mc = Pattern.compile("_").matcher(param);
            int i = 0;
            while (mc.find()) {
                int position = mc.end() - (i++);
                sb.replace(position - 1, position + 1, sb.substring(position, position + 1).toUpperCase());
            }
            return sb.toString();
        }
    
        public static void main(String[] args) {
            String aaa = "app_version_fld";
            System.out.println(underlineToCamel(aaa));
            System.out.println(underlineToCamel2(aaa));
            aaa = "appVersionFld";
            System.out.println(camelToUnderline(aaa));
        
        }
  • 相关阅读:
    请求转发和重定向
    jvm调优(新生代、老年代调优)
    servlet(对servlet的理解、生命周期)
    http的get和post请求方式
    jvm垃圾回收器(串行、吞吐量优先、响应时间优先、G1)
    java后端学习路线总结
    jvm:java中的引用(强引用、软引用、虚引用、弱引用)
    jvm直接内存(分配与回收)
    ssm(增删改查、拦截器、过滤器)
    springmvc:文件的上传与下载
  • 原文地址:https://www.cnblogs.com/franson-2016/p/6169138.html
Copyright © 2011-2022 走看看