将 Java 字符串从全部大写(由下划线分隔的单词)转换为 CamelCase(无单词分隔符)的最简单方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1143951/
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
What is the simplest way to convert a Java string from all caps (words separated by underscores) to CamelCase (no word separators)?
提问by Matt Ball
The title pretty much says it all. What's the simplest/most elegant way that I can convert, in Java, a string from the format "THIS_IS_AN_EXAMPLE_STRING"
to the format "ThisIsAnExampleString
"? I figure there must be at least one way to do it using String.replaceAll()
and a regex.
标题基本概括了所有内容。我可以在 Java 中将字符串从格式"THIS_IS_AN_EXAMPLE_STRING"
转换为格式“ ThisIsAnExampleString
”的最简单/最优雅的方法是什么?我认为必须至少有一种方法可以使用String.replaceAll()
正则表达式。
My initial thoughts are: prepend the string with an underscore (_
), convert the whole string to lower case, and then use replaceAll to convert every character preceded by an underscore with its uppercase version.
我最初的想法是:在字符串前面加上下划线 ( _
),将整个字符串转换为小写,然后使用 replaceAll 将下划线前面的每个字符转换为大写版本。
采纳答案by Arnout Engelen
Another option is using Google Guava's com.google.common.base.CaseFormat
另一种选择是使用谷歌番石榴的 com.google.common.base.CaseFormat
George Hawkinsleft a comment with this example of usage:
乔治·霍金斯 (George Hawkins)留下了这个用法示例的评论:
CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, "THIS_IS_AN_EXAMPLE_STRING");
回答by C. Ross
static String toCamelCase(String s){
String[] parts = s.split("_");
String camelCaseString = "";
for (String part : parts){
camelCaseString = camelCaseString + toProperCase(part);
}
return camelCaseString;
}
static String toProperCase(String s) {
return s.substring(0, 1).toUpperCase() +
s.substring(1).toLowerCase();
}
Note: You need to add argument validation.
注意:您需要添加参数验证。
回答by Alex B
Here is a code snippet which might help:
这是一个可能有帮助的代码片段:
String input = "ABC_DEF";
StringBuilder sb = new StringBuilder();
for( String oneString : input.toLowerCase().split("_") )
{
sb.append( oneString.substring(0,1).toUpperCase() );
sb.append( oneString.substring(1) );
}
// sb now holds your desired String
回答by Dan Gravell
Take a look at WordUtils in the Apache Commons langlibrary:
看看Apache Commons lang库中的 WordUtils:
Specifically, the capitalizeFully(String str, char[] delimiters) method should do the job:
具体来说, capitalizeFully(String str, char[] delimiters) 方法应该完成这项工作:
String blah = "LORD_OF_THE_RINGS";
assertEquals("LordOfTheRings", WordUtils.capitalizeFully(blah, new char[]{'_'}).replaceAll("_", ""));
Green bar!
绿条!
回答by Yishai
public static void main(String[] args) {
String start = "THIS_IS_A_TEST";
StringBuffer sb = new StringBuffer();
for (String s : start.split("_")) {
sb.append(Character.toUpperCase(s.charAt(0)));
if (s.length() > 1) {
sb.append(s.substring(1, s.length()).toLowerCase());
}
}
System.out.println(sb);
}
回答by Hendy Irawan
You can use org.modeshape.common.text.Inflector.
您可以使用org.modeshape.common.text.Inflector。
Specifically:
具体来说:
String camelCase(String lowerCaseAndUnderscoredWord, boolean uppercaseFirstLetter, char... delimiterChars)
By default, this method converts strings to UpperCamelCase.
String camelCase(String lowerCaseAndUnderscoredWord, boolean uppercaseFirstLetter, char... delimiterChars)
默认情况下,此方法将字符串转换为大写字母。
Maven artifact is: org.modeshape:modeshape-common:2.3.0.Final
Maven 工件是:org.modeshape:modeshape-common:2.3.0.Final
on JBoss repository: https://repository.jboss.org/nexus/content/repositories/releases
在 JBoss 存储库上:https: //repository.jboss.org/nexus/content/repositories/releases
Here's the JAR file: https://repository.jboss.org/nexus/content/repositories/releases/org/modeshape/modeshape-common/2.3.0.Final/modeshape-common-2.3.0.Final.jar
这是 JAR 文件:https: //repository.jboss.org/nexus/content/repositories/releases/org/modeshape/modeshape-common/2.3.0.Final/modeshape-common-2.3.0.Final.jar
回答by leorleor
Not sure, but I think I can use less memory and get dependable performance by doing it char-by-char. I was doing something similar, but in loops in background threads, so I am trying this for now. I've had some experience with String.split being more expensive then expected. And I am working on Android and expect GC hiccups to be more of an issue then cpu use.
不确定,但我认为我可以使用更少的内存并通过逐个字符进行操作来获得可靠的性能。我正在做类似的事情,但是在后台线程的循环中,所以我现在正在尝试这个。我有一些经验,String.split 比预期的要贵。而且我正在开发 Android 并希望 GC 打嗝比 cpu 使用更重要。
public static String toCamelCase(String value) {
StringBuilder sb = new StringBuilder();
final char delimChar = '_';
boolean lower = false;
for (int charInd = 0; charInd < value.length(); ++charInd) {
final char valueChar = value.charAt(charInd);
if (valueChar == delimChar) {
lower = false;
} else if (lower) {
sb.append(Character.toLowerCase(valueChar));
} else {
sb.append(Character.toUpperCase(valueChar));
lower = true;
}
}
return sb.toString();
}
A hint that String.split is expensive is that its input is a regex (not a char like String.indexOf) and it returns an array (instead of say an iterator because the loop only uses one things at a time). Plus cases like "AB_AB_AB_AB_AB_AB..." break the efficiency of any bulk copy, and for long strings use an order of magnitude more memory then the input string.
String.split 很昂贵的一个提示是它的输入是一个正则表达式(不是像 String.indexOf 那样的字符)并且它返回一个数组(而不是说一个迭代器,因为循环一次只使用一个东西)。加上像“AB_AB_AB_AB_AB_AB...”这样的情况会破坏任何批量复制的效率,对于长字符串,使用比输入字符串多一个数量级的内存。
Whereas looping through chars has no canonical case. So to me the overhead of an unneeded regex and array seems generally less preferable (then giving up possible bulk copy efficiency). Interested to hear opinions / corrections, thanks.
而循环遍历字符没有规范的情况。所以对我来说,不需要的正则表达式和数组的开销通常不太可取(然后放弃可能的批量复制效率)。有兴趣听取意见/更正,谢谢。
回答by Srisa
public String withChars(String inputa) {
String input = inputa.toLowerCase();
StringBuilder sb = new StringBuilder();
final char delim = '_';
char value;
boolean capitalize = false;
for (int i=0; i<input.length(); ++i) {
value = input.charAt(i);
if (value == delim) {
capitalize = true;
}
else if (capitalize) {
sb.append(Character.toUpperCase(value));
capitalize = false;
}
else {
sb.append(value);
}
}
return sb.toString();
}
public String withRegex(String inputa) {
String input = inputa.toLowerCase();
String[] parts = input.split("_");
StringBuilder sb = new StringBuilder();
sb.append(parts[0]);
for (int i=1; i<parts.length; ++i) {
sb.append(parts[i].substring(0,1).toUpperCase());
sb.append(parts[i].substring(1));
}
return sb.toString();
}
Times:in milli seconds.
时间:以毫秒为单位。
Iterations = 1000
WithChars: start = 1379685214671 end = 1379685214683 diff = 12
WithRegex: start = 1379685214683 end = 1379685214712 diff = 29
Iterations = 1000
WithChars: start = 1379685217033 end = 1379685217045 diff = 12
WithRegex: start = 1379685217045 end = 1379685217077 diff = 32
Iterations = 1000
WithChars: start = 1379685218643 end = 1379685218654 diff = 11
WithRegex: start = 1379685218655 end = 1379685218684 diff = 29
Iterations = 1000000
WithChars: start = 1379685232767 end = 1379685232968 diff = 201
WithRegex: start = 1379685232968 end = 1379685233649 diff = 681
Iterations = 1000000
WithChars: start = 1379685237220 end = 1379685237419 diff = 199
WithRegex: start = 1379685237419 end = 1379685238088 diff = 669
Iterations = 1000000
WithChars: start = 1379685239690 end = 1379685239889 diff = 199
WithRegex: start = 1379685239890 end = 1379685240585 diff = 695
Iterations = 1000000000
WithChars: start = 1379685267523 end = 1379685397604 diff = 130081
WithRegex: start = 1379685397605 end = 1379685850582 diff = 452977
回答by Ashish
You can Try this also :
你也可以试试这个:
public static String convertToNameCase(String s)
{
if (s != null)
{
StringBuilder b = new StringBuilder();
String[] split = s.split(" ");
for (String srt : split)
{
if (srt.length() > 0)
{
b.append(srt.substring(0, 1).toUpperCase()).append(srt.substring(1).toLowerCase()).append(" ");
}
}
return b.toString().trim();
}
return s;
}
回答by librucha
With Apache Commons Lang3 lib is it very easy.
使用 Apache Commons Lang3 lib 非常容易。
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.text.WordUtils;
public String getName(String text) {
return StringUtils.remove(WordUtils.capitalizeFully(text, '_'), "_");
}
Example:
例子:
getName("SOME_CONSTANT");
Gives:
给出:
"SomeConstant"