Java实现驼峰、下划线互转
1.使用 Guava 实现
先引入相关依赖
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>21.0</version>
</dependency>
```1
1.1 驼峰转下划线
```java
public static void main(String[] args) {
String resultStr = CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, "userName");
System.out.println("转换后结果是:"+resultStr);
}
转换后结果是:user_name
1.2 下划线转驼峰
public static void main(String[] args) {
String resultStr = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, "user_name");
System.out.println("转换后结果是:"+resultStr);
}
转换后结果是:userName
2.自定义代码转
2.1驼峰转下划线
private static final Pattern TPATTERN = Pattern.compile("[A-Z0-9]");
private String teseDemo(String str) {
Matcher matcher = TPATTERN.matcher(str);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
}
matcher.appendTail(sb);
return sb.toString();
}
2.2下划线转驼峰文章来源:https://www.toymoban.com/news/detail-531682.html
private static final char UNICON = '_';
private String underlineToCamel(String param) {
if (StringUtils.isBlank(param)) {
return "";
}
int len = param.length();
StringBuilder sb = new StringBuilder(len);
for (int i = 0; i < len; i++) {
char c = Character.toLowerCase(param.charAt(i));
if (c == UNICON) {
if (++i < len) {
sb.append(Character.toUpperCase(param.charAt(i)));
}
} else {
sb.append(c);
}
}
return sb.toString();
}
文章来源地址https://www.toymoban.com/news/detail-531682.html
到了这里,关于Java实现驼峰、下划线互转的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!