将Javastring从全部大写字母(由下划线分隔的string)转换为CamelCase(无字分隔符)的最简单方法是什么?
标题基本概括了所有内容。 什么是最简单/最优雅的方式,我可以在Java中将string从"THIS_IS_AN_EXAMPLE_STRING"
格式转换为"THIS_IS_AN_EXAMPLE_STRING"
格式? 我认为必须至less有一种方法来使用String.replaceAll()
和正则expression式。
我最初的想法是:用下划线( _
)前缀string,将整个string转换为小写,然后使用replaceAll将每个字符前面带有下划线的大写版本转换。
另一个select是使用Google Guava的com.google.common.base.CaseFormat
乔治·霍金斯(George Hawkins)对这个用法的例子留下评论:
CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, "THIS_IS_AN_EXAMPLE_STRING");
看看Apache Commons lang库中的WordUtils :
具体来说,大写(String str,char []分隔符)方法应该做的工作:
String blah = "LORD_OF_THE_RINGS"; assertEquals("LordOfTheRings", WordUtils.capitalizeFully(blah, new char[]{'_'}).replaceAll("_", ""));
绿吧!
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(); }
注意 :您需要添加参数validation。
与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, '_'), "_"); }
例:
getName("SOME_CONSTANT");
得到:
"SomeConstant"
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); }
这是一个代码片段,可能有助于:
String input = "ABC_DEF"; StringBuilder sb = new StringBuilder(); for( String oneString : input.split("_") ) { sb.append( oneString.substring(0,1) ); sb.append( oneString.substring(1).toLowerCase() ); } // sb now holds your desired String
不知道,但我想我可以使用更less的内存,并通过逐字符地获得可靠的性能。 我正在做类似的事情,但在后台线程循环,所以我现在正在尝试这个。 我已经有一些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(); }
一个提示,String.split是昂贵的是,它的input是一个正则expression式(而不是像String.indexOf字符),它返回一个数组(而不是一个迭代器,因为循环一次只使用一个东西)。 再加上像“AB_AB_AB_AB_AB_AB …”这样的情况会破坏任何批量复制的效率,对于长string,inputstring的内存使用的数量级要多一个数量级。
循环字符没有规范的情况。 所以对我来说,不必要的正则expression式和数组的开销通常不太可取(然后放弃可能的批量复制效率)。 有兴趣听到意见/更正,谢谢。
使用Streams的Java 1.8示例
String text = "THIS_IS_SOME_TEXT"; String bactrianCamel = Stream.of(text.split("[^a-zA-Z0-9]")) .map(v -> v.substring(0, 1).toUpperCase() + v.substring(1).toLowerCase()) .collect(Collectors.joining()); String dromedaryCamel = bactrianCamel.toLowerCase().substring(0, 1) + bactrianCamel.substring(1); System.out.printf("%s is now %s%n", text, dromedaryCamel);
THIS_IS_SOME_TEXT现在是thisIsSomeText
你可以使用org.modeshape.common.text.Inflector 。
特别:
String camelCase(String lowerCaseAndUnderscoredWord, boolean uppercaseFirstLetter, char... delimiterChars)
默认情况下,此方法将string转换为UpperCamelCase。
Maven神器是: org.modeshape:modeshape-common:2.3.0.Final
在JBoss仓库上: https : //repository.jboss.org/nexus/content/repositories/releases
这里是JAR文件: https : //repository.jboss.org/nexus/content/repositories/releases/org/modeshape/modeshape-common/2.3.0.Final/modeshape-common-2.3.0.Final.jar
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(); }
时间:以毫秒为单位。
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
你也可以试试这个:
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; }
它会将Enum Constant
转换为Camel Case。 任何正在寻找这种function的人都会很有帮助。
public enum TRANSLATE_LANGUAGES { ARABIC("ar"), BULGARIAN("bg"), CATALAN("ca"), CHINESE_SIMPLIFIED("zh-CN"), CHINESE_TRADITIONAL("zh-TW"), CZECH("cs"), DANISH("da"), DUTCH("nl"), ENGLISH("en"), ESTONIAN("et"), FINNISH("fi"), FRENCH( "fr"), GERMAN("de"), GREEK("el"), HAITIAN_CREOLE("ht"), HEBREW("he"), HINDI("hi"), HMONG_DAW("mww"), HUNGARIAN("hu"), INDONESIAN("id"), ITALIAN("it"), JAPANESE("ja"), KOREAN("ko"), LATVIAN( "lv"), LITHUANIAN("lt"), MALAY("ms"), NORWEGIAN("no"), PERSIAN("fa"), POLISH("pl"), PORTUGUESE("pt"), ROMANIAN("ro"), RUSSIAN("ru"), SLOVAK("sk"), SLOVENIAN("sl"), SPANISH("es"), SWEDISH( "sv"), THAI("th"), TURKISH("tr"), UKRAINIAN("uk"), URDU("ur"), VIETNAMESE("vi"); private String code; TRANSLATE_LANGUAGES(String language) { this.code = language; } public String langCode() { return this.code; } public String toCamelCase(TRANSLATE_LANGUAGES lang) { String toString = lang.toString(); if (toString.contains("_")) { String st = toUpperLowerCase(toString.split("_")); } return ""; } private String toUpperLowerCase(String[] tempString) { StringBuilder builder = new StringBuilder(); for (String temp : tempString) { String char1 = temp.substring(0, 1); String restString = temp.substring(1, temp.length()).toLowerCase(); builder.append(char1).append(restString).append(" "); } return builder.toString(); } }
还有一个解决办法可能如下。
public static String toCamelCase(String str, String... separators) { String separatorsRegex = "\\".concat(org.apache.commons.lang3.StringUtils.join(separators, "|\\")); List splits = Arrays.asList(str.toLowerCase().split(separatorsRegex)); String capitalizedString = (String)splits.stream().map(WordUtils::capitalize).reduce("", String::concat); return capitalizedString.substring(0, 1).toLowerCase() + capitalizedString.substring(1); }
public static final String UPPER_CAMEL = "initUp"; public static final String LOWER_CAMEL = "initLow"; public String toCamel(String src, String separator, String format) { StringBuilder builder = new StringBuilder(src.toLowerCase()); int len = builder.length(); for (int idx = builder.indexOf(separator); idx > 0 && idx < len; idx = builder.indexOf(separator, idx)) { builder = builder.replace(idx, idx + 2, (String.valueOf(builder.charAt(idx + 1)).toUpperCase())); } switch (format) { case LOWER_CAMEL: builder.setCharAt(0, Character.toLowerCase(builder.charAt(0))); break; default: builder.setCharAt(0, Character.toUpperCase(builder.charAt(0))); break; } return builder.toString(); }
调用为
toCamel("THIS_IS_AN_EXAMPLE_STRING", "_", UPPER_CAMEL)
执行时间:14 ms
protected String toCamelCase(String input) { if (input == null) { return null; } if (input.length() == 0) { return ""; } // lowercase the first character String camelCaseStr = input.substring(0, 1).toLowerCase(); if (input.length() > 1) { boolean isStartOfWord = false; for (int i = 1; i < input.length(); i++) { char currChar = input.charAt(i); if (currChar == '_') { // new word. ignore underscore isStartOfWord = true; } else if (Character.isUpperCase(currChar)) { // capital letter. if start of word, keep it if (isStartOfWord) { camelCaseStr += currChar; } else { camelCaseStr += Character.toLowerCase(currChar); } isStartOfWord = false; } else { camelCaseStr += currChar; isStartOfWord = false; } } } return camelCaseStr; }
public String CamelCase(String str) { String CamelCase=""; String parts[] = str.split("_"); for(String part:parts) { String as=part.toLowerCase(); int a=as.length(); CamelCase = CamelCase + as.substring(0, 1).toUpperCase()+ as.substring(1,a); } return CamelCase; }
这是最简单的程序转换成CamelCase。 希望它会帮助你..
一个简单的snnipet:
public static String camelCase(String in) { if (in == null || in.length() < 1) { return ""; } //validate in String out = ""; for (String part : in.toLowerCase().split("_")) { if (part.length() < 1) { //validate length continue; } out += part.substring(0, 1).toUpperCase(); if (part.length() > 1) { //validate length out += part.substring(1); } } return out; }