java Java中从snake_case到camelCase
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34228942/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
From snake_case to camelCase in Java
提问by Domenico
Can anyone tell me how to convert a string in snake_case as:
谁能告诉我如何将snake_case中的字符串转换为:
camel_case
to a string in camelCase as:
到camelCase中的字符串为:
camelCase
in Java?
在爪哇?
Thank you in advance.
先感谢您。
回答by Sher Alam
This might be pretty, and it works
这可能很漂亮,而且有效
public class Test {
public static void main(String[] args) {
String phrase = "always_use_camel_back_notation_in_java";
while(phrase.contains("_")) {
phrase = phrase.replaceFirst("_[a-z]", String.valueOf(Character.toUpperCase(phrase.charAt(phrase.indexOf("_") + 1))));
}
System.out.println(phrase);
}
}
回答by Luís Soares
You can use toCamelCase
util:
您可以使用工具toCamelCase
:
CaseUtils.toCamelCase("camel_case", false, new char[]{'_'}); // returns "camelCase"
from Apache Commons Text.
回答by Noam Hacker
Take a look at oracle's documentation for the stringclass, notably substring, charAt, indexOf, and toUpperCase
查看字符串类的oracle 文档,特别是substring、charAt、indexOf和toUpperCase
(You can use these as puzzle pieces to solve your problem)
(您可以将这些用作拼图来解决您的问题)
回答by Alex
Also Guava's CaseFormatoffers quite a neat solution that allows you to transform from and to camel case and even other specific cases.
Guava 的CaseFormat还提供了一个非常简洁的解决方案,允许您在驼峰案例甚至其他特定案例之间进行转换。
CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, "camel_case"); // returns camelCase
CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, "CAMEL_CASE"); // returns CamelCase
CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, "camelCase"); // returns CAMEL_CASE
CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, "CamelCase"); // returns camel-case
回答by hallgren
This isn't pretty, but it works:
这并不漂亮,但它有效:
String phrase = "camel_case";
String[] words = phrase.split("_");
String newPhrase = words[0];
for(int i=1; i<words.length; i++) newPhrase += words[i].substring(0,1).toUpperCase() + words[i].substring(1);
回答by OneCricketeer
Using split("_")
and looping over those parts is one way to do it.
使用split("_")
和循环这些部分是一种方法。
Here is an alternative using a StringBuilder
.
这是使用StringBuilder
.
String s = "make_me_camel_case";
StringBuilder sb = new StringBuilder(s);
for (int i = 0; i < sb.length(); i++) {
if (sb.charAt(i) == '_') {
sb.deleteCharAt(i);
sb.replace(i, i+1, String.valueOf(Character.toUpperCase(sb.charAt(i))));
}
}
System.out.println(sb.toString()); // makeMeCamelCase