Java實(shí)現(xiàn)駝峰、下劃線互轉(zhuǎn)
1.使用 Guava 實(shí)現(xiàn)
先引入相關(guān)依賴
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>21.0</version>
</dependency>
```1
1.1 駝峰轉(zhuǎn)下劃線
```java
public static void main(String[] args) {
String resultStr = CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, "userName");
System.out.println("轉(zhuǎn)換后結(jié)果是:"+resultStr);
}
轉(zhuǎn)換后結(jié)果是:user_name
1.2 下劃線轉(zhuǎn)駝峰
public static void main(String[] args) {
String resultStr = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, "user_name");
System.out.println("轉(zhuǎn)換后結(jié)果是:"+resultStr);
}
轉(zhuǎn)換后結(jié)果是:userName
2.自定義代碼轉(zhuǎn)
2.1駝峰轉(zhuǎn)下劃線
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下劃線轉(zhuǎn)駝峰文章來源:http://www.zghlxwxcb.cn/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();
}
文章來源地址http://www.zghlxwxcb.cn/news/detail-531682.html
到了這里,關(guān)于Java實(shí)現(xiàn)駝峰、下劃線互轉(zhuǎn)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!