Java中字符串下划线和驼峰之间的转换(万能工具包hutool)

下划线转驼峰

public static void main(String[] args) {
        HashMap<String,Object> extMap = new HashMap<>();
        extMap.put("ORGAN_NAME","四个空格");
        extMap.put("WEB_SITE","https://www.4spaces.org");
        HashMap camelcaseExtMap = new HashMap();
        for (Map.Entry<String,Object> entry:extMap.entrySet()){
            camelcaseExtMap.put(strByKey(entry.getKey(),"_"),entry.getValue());

            System.out.println(strByKey(entry.getKey(),"_")+","+entry.getValue());
        }
    }

    public static String strByKey(String mapKey,String chart){
        String[] split = mapKey.split(chart);
        StringBuilder sbui = new StringBuilder();
        for (int i = 0; i < split.length; i++) {
            if (i==0){
                sbui.append(split[0].toLowerCase());
            }else {
                sbui.append(split[i].charAt(0)+split[i].substring(1).toLowerCase());
            }
        }
        return sbui.toString();
    }

字符串驼峰转下划线

1.正则式转换

/**
     * @author Howe
     * @Description 将驼峰转为下划线,正则式
     * @param str  例如:helloWord
     * @return java.lang.String
     * underline:下划线,驼峰:hump
     */
    public static Pattern compile = Pattern.compile("[A-Z]");
    public static String underlineByhump(String str) {

        Matcher matcher = compile.matcher(str);
        StringBuffer sb = new StringBuffer();
        while(matcher.find()) {
            matcher.appendReplacement(sb,  "_" + matcher.group(0).toLowerCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

2.maven依赖hutool-all方式实现
(1)maven依赖

<dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.5.9</version>
        </dependency>

(2)使用

String string = "helloWord";
String strCase = StrUtil.toUnderlineCase(string);
System.out.println("strCase = " + strCase);

Java中字符串下划线和驼峰之间的转换(万能工具包hutool)_第1张图片

3.hutool-all依赖包的实用

hutool介绍
(1).生成UUID字符串
(2).数据校验
(3).JSON解析

https://blog.csdn.net/WNX10086/article/details/122294558

你可能感兴趣的:(java,开发语言)