字符串驼峰和下划线格式互转

原文链接:https://juejin.cn/post/7106521793934360584


依赖

# 
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>31.1-jre</version>
</dependency>

单次转换

import com.google.common.base.Ascii;
import com.google.common.base.CaseFormat;
import com.google.common.base.Converter;


CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_UNDERSCORE, "family_name_and_last_name"));   // family_name_and_last_name
CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_UNDERSCORE, "family_name_and_last_name"));   // FAMILY_NAME_AND_LAST_NAME
CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, "family_name_and_last_name"));        // familyNameAndLastName
CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, "family_name_and_last_name"));        // FamilyNameAndLastName
CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_HYPHEN, "family_name_and_last_name"));       // family-name-and-last-name

定义转换器

String result = lowerUpperUnderscore("family_name_and_last_name"); // FAMILY_NAME_AND_LAST_NAME

private String lowerUpperUnderscore(String str) {
    Converter<String, String> converter = CaseFormat.LOWER_UNDERSCORE.converterTo(CaseFormat.UPPER_UNDERSCORE);
    return converter.convert(str);
}

你可能感兴趣的:(基础知识,共通方法,最佳实践,java,数据库,开发语言)