java 需要将lowercase_underscore字符串更改为camelCase
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17061300/
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
Need to change lowercase_underscore string to camelCase
提问by Deckard
I Need to change String : underbar + lowercase = uppercase.(and the opposite)
我需要更改字符串:下划线 + 小写 = 大写。(反之亦然)
my_name -> myName
Is there any library or something to help this out?
有没有图书馆或其他东西可以帮助解决这个问题?
回答by gma
You can use the CaseFormat
class's LOWER_UNDERSCORE
from google Guava:
您可以使用来自 google Guava的CaseFormat
课程LOWER_UNDERSCORE
:
CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, "my_name")
回答by Evgeniy Dorofeev
I suggest a custom solution
我建议自定义解决方案
Pattern p = Pattern.compile("_(.)");
Matcher m = p.matcher("my_name");
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, m.group(1).toUpperCase());
}
m.appendTail(sb);
System.out.println(sb.toString());
output
输出
myName
回答by obourgain
CaseFormat
is an utility class in Google Guava for converting between case conventions.
CaseFormat
是 Google Guava 中的一个实用程序类,用于在大小写约定之间进行转换。
回答by Miroslaw Dylag
Another solution is to use StringTokenizer:
另一种解决方案是使用 StringTokenizer:
String value = "id_app";
StringTokenizer toekn = new StringTokenizer(value,"_");
StringBuilder str = new StringBuilder(toekn.nextToken());
while (toekn.hasMoreTokens()) {
String s = toekn.nextToken();
str.append(Character.toUpperCase(s.charAt(0))).append(s.substring(1));
}
System.out.println(str.toString());
回答by SrinivasM
String s="My_name";
int i=s.indexOf('_');
s=s.replaceFirst(Character.toString(s.charAt(i+1)),Character.toString(Character.toUpperCase(s.charAt(i+1))));
s=s.replaceAll("_","");
回答by Hari Das
Check this code, I have verified it.
检查此代码,我已验证它。
String str = new String("my_name");
for(int i=0;i<str.length()-1;i++){
if(str.charAt(i)=='_' && (int) str.charAt(i+1)>=97 && (int) str.charAt(i+1)<=122){
str=str.replace(str.substring(i, i+2),""+(char)((int) str.charAt(i+1)-32));
}
}
System.out.println(str);
回答by SrinivasM
String s="srinivas";
s=s.replaceFirst(Character.toString(s.charAt(0)),
Character.toString(Character.toUpperCase(s.charAt(0))));
//s Value is "Srinivas" now
回答by user7294900
You can replace lower case character following underscore with uppercase using appendReplacement
您可以使用appendReplacement用大写替换下划线后面的小写字符
The appendReplacement and appendTail methods can be used in tandem in order to collect the result into an existing string buffer
appendReplacement 和 appendTail 方法可以串联使用,以便将结果收集到现有的字符串缓冲区中
String text = "my_name_is";
Matcher m = Pattern.compile("([_][a-z])").matcher(text);
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, m.group().substring(1).toUpperCase());
}
m.appendTail(sb);