Java 将连字符分隔的单词(例如“do-some-stuff”)转换为较小的驼峰变体(例如“doSomeStuff”)的最优雅方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3618733/
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 most elegant way to convert a hyphen separated word (e.g. "do-some-stuff") to the lower camel-case variation (e.g. "doSomeStuff")?
提问by Christopher Klewes
What is the most elegant way to convert a hyphen separated word (e.g. "do-some-stuff") to the lower camel-case variation (e.g. "doSomeStuff") in Java?
在 Java 中将连字符分隔的单词(例如“do-some-stuff”)转换为较小的驼峰变体(例如“doSomeStuff”)的最优雅的方法是什么?
采纳答案by Joachim Sauer
Use CaseFormat
from Guava:
CaseFormat
从番石榴中使用:
import static com.google.common.base.CaseFormat.*;
String result = LOWER_HYPHEN.to(LOWER_CAMEL, "do-some-stuff");
回答by Daren Thomas
Why not try this:
为什么不试试这个:
- split on "-"
- uppercase each word, skipping the first
- join
- 在“-”上拆分
- 大写每个单词,跳过第一个
- 加入
EDIT: On second thoughts... While trying to implement this, I found out there is no simple way to join a list of strings in Java. Unless you use StringUtil
from apache. So you will need to create a StringBuilder
anyway and thus the algorithm is going to get a little ugly :(
编辑:再想一想......在尝试实现这一点时,我发现没有简单的方法可以在 Java 中加入字符串列表。除非你StringUtil
从 apache使用。所以你StringBuilder
无论如何都需要创建一个,因此算法会变得有点难看:(
CODE: Here is a sample of the above mentioned aproach. Could someone with a Java compiler (sorry, don't have one handy) test this? And benchmark it with other versions found here?
代码:这是上述方法的示例。有 Java 编译器的人(抱歉,手边没有)可以测试这个吗?并使用此处找到的其他版本对其进行基准测试?
public static String toJavaMethodNameWithSplits(String xmlMethodName)
{
String[] words = xmlMethodName.split("-"); // split on "-"
StringBuilder nameBuilder = new StringBuilder(xmlMethodName.length());
nameBuilder.append(words[0]);
for (int i = 1; i < words.length; i++) // skip first
{
nameBuilder.append(words[i].substring(0, 1).toUpperCase());
nameBuilder.append(words[i].substring(1));
}
return nameBuilder.toString(); // join
}
回答by Noel M
Iterate through the string. When you find a hypen, remove it, and capitalise the next letter.
遍历字符串。找到连字符后,将其删除,然后将下一个字母大写。
回答by Andreas Dolk
The following method should handle the task quite efficient in O(n). We just iterate over the characters of the xml method name, skip any '-' and capitalize chars if needed.
以下方法应该在 O(n) 中非常有效地处理任务。我们只是遍历 xml 方法名称的字符,跳过任何“-”并在需要时将字符大写。
public static String toJavaMethodName(String xmlmethodName) {
StringBuilder nameBuilder = new StringBuilder(xmlmethodName.length());
boolean capitalizeNextChar = false;
for (char c:xmlMethodName.toCharArray()) {
if (c == '-') {
capitalizeNextChar = true;
continue;
}
if (capitalizeNextChar) {
nameBuilder.append(Character.toUpperCase(c));
} else {
nameBuilder.append(c);
}
capitalizeNextChar = false;
}
return nameBuilder.toString();
}
回答by Sean Patrick Floyd
Here is a slight variation of Andreas' answerthat does more than the OP asked for:
这是Andreas 的答案的一个细微变化,它比 OP 要求的要多:
public static String toJavaMethodName(final String nonJavaMethodName){
final StringBuilder nameBuilder = new StringBuilder();
boolean capitalizeNextChar = false;
boolean first = true;
for(int i = 0; i < nonJavaMethodName.length(); i++){
final char c = nonJavaMethodName.charAt(i);
if(!Character.isLetterOrDigit(c)){
if(!first){
capitalizeNextChar = true;
}
} else{
nameBuilder.append(capitalizeNextChar
? Character.toUpperCase(c)
: Character.toLowerCase(c));
capitalizeNextChar = false;
first = false;
}
}
return nameBuilder.toString();
}
It handles a few special cases:
它处理一些特殊情况:
fUnnY-cASe
is converted tofunnyCase
--dash-before-and--after-
is converted todashBeforeAndAfter
some.other$funky:chars?
is converted tosomeOtherFunkyChars
fUnnY-cASe
转换为funnyCase
--dash-before-and--after-
转换为dashBeforeAndAfter
some.other$funky:chars?
转换为someOtherFunkyChars
回答by Arne Deutsch
If you don't like to depend on a library you can use a combination of a regex and String.format
. Use a regex to extract the starting characters after the -
. Use these as input for String.format
. A bit tricky, but works without a (explizit) loop ;).
如果您不喜欢依赖库,您可以使用正则表达式和String.format
. 使用正则表达式提取-
. 将这些用作String.format
. 有点棘手,但无需(explizit)循环即可工作;)。
public class Test {
public static void main(String[] args) {
System.out.println(convert("do-some-stuff"));
}
private static String convert(String input) {
return String.format(input.replaceAll("\-(.)", "%S"), input.replaceAll("[^-]*-(.)[^-]*", "-").split("-"));
}
}
回答by Sean
get The Apache commons jar for StringUtils. Then you can use the capitalize method
获取 StringUtils 的 Apache commons jar。然后你可以使用capitalize方法
import org.apache.commons.lang.StringUtils;
public class MyClass{
public String myMethod(String str) {
StringBuffer buff = new StringBuffer();
String[] tokens = str.split("-");
for (String i : tokens) {
buff.append(StringUtils.capitalize(i));
}
return buff.toString();
}
}
回答by Pierre Lemée
As I'm not a big fan of adding a library just for one method, I implemented my own solution (from camel case to snake case):
由于我不喜欢为一种方法添加库,因此我实现了自己的解决方案(从骆驼案例到蛇案例):
public String toSnakeCase(String name) {
StringBuilder buffer = new StringBuilder();
for(int i = 0; i < name.length(); i++) {
if(Character.isUpperCase(name.charAt(i))) {
if(i > 0) {
buffer.append('_');
}
buffer.append(Character.toLowerCase(name.charAt(i)));
} else {
buffer.append(name.charAt(i));
}
}
return buffer.toString();
}
Needs to be adapted depending of the in / out cases.
需要根据输入/输出情况进行调整。
回答by earcam
With Java 8there is finally a one-liner:
在 Java 8 中,终于有一个单行了:
Arrays.stream(name.split("\-"))
.map(s -> Character.toUpperCase(s.charAt(0)) + s.substring(1).toLowerCase())
.collect(Collectors.joining());
Though it takes splitting over 3 actuallines to be legible ツ
虽然需要拆分 3行实际行才能清晰 ツ
(Note: "\\-"
is for kebab-case as per question, for snake_case simply change to "_"
)
(注意:"\\-"
针对每个问题的 kebab-case,对于 snake_case 只需更改为"_"
)
回答by Chi Dov
For those who has com.fasterxml.Hymanson library in the project and don't want to add guava you can use the jaskson namingStrategy method:
对于那些在项目中有 com.fasterxml.Hymanson 库并且不想添加 guava 的人,您可以使用 jaskson 命名策略方法:
new PropertyNamingStrategy.SnakeCaseStrategy.translate(String);