将Java字符串从所有大写字母(由下划线分隔的单词)转换为CamelCase(无单词分隔符)的最简单方法是什么?

时间:2009-07-17 15:19:36

标签: java regex string

标题几乎说明了一切。我能用Java格式转换格式为"THIS_IS_AN_EXAMPLE_STRING"到格式为“ThisIsAnExampleString”的字符串的最简单/最优雅的方法是什么?我认为必须至少有一种方法可以使用String.replaceAll()和正则表达式。

我最初的想法是:在字符串前面添加下划线(_),将整个字符串转换为小写字母,然后使用replaceAll将每个前面带下划线的字符转换为大写字母。

21 个答案:

答案 0 :(得分:161)

另一种选择是使用Google Guava的com.google.common.base.CaseFormat

George Hawkins在此使用示例中留下了评论:

CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, "THIS_IS_AN_EXAMPLE_STRING");

答案 1 :(得分:112)

查看WordUtils in the Apache Commons lang库:

具体来说,capitalizeFully(String str,char [] delimiters)方法应该完成这项工作:

String blah = "LORD_OF_THE_RINGS";
assertEquals("LordOfTheRings", WordUtils.capitalizeFully(blah, new char[]{'_'}).replaceAll("_", ""));

绿色吧!

答案 2 :(得分:80)

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();
}

注意:您需要添加参数验证。

答案 3 :(得分:16)

使用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"

答案 4 :(得分:9)

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);
}

答案 5 :(得分:5)

以下是可能有用的代码段:

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

答案 6 :(得分:4)

使用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

答案 7 :(得分:2)

不确定,但我认为我可以使用更少的内存并通过char-by-char获得可靠的性能。我正在做类似的事情,但是在后台线程循环中,所以我现在正在尝试这个。我有一些使用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很昂贵的提示是它的输入是一个正则表达式(不是像String.indexOf那样的char)并且它返回一个数组(而不是说迭代器,因为循环一次只使用一个东西)。像“AB_AB_AB_AB_AB_AB ...”这样的情况会破坏任何批量复制的效率,对于长字符串,使用比输入字符串多一个数量级的内存。

而循环通过字符没有规范的情况。所以对我来说,不需要的正则表达式和数组的开销通常不太可取(然后放弃可能的批量复制效率)。有兴趣听取意见/更正,谢谢。

答案 8 :(得分:2)

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

答案 9 :(得分:1)

public static String toCamelCase(String value) {
    value = value.replace("_", " ");
    String[] parts = value.split(" ");
    int i = 0;
    String camelCaseString = "";
    for (String part : parts) {
        if (part != null && !part.isEmpty()) {
            if (i == 0) {
                camelCaseString = part.toLowerCase();
            } else if (i > 0 && part.length() > 1) {
                String oldFirstChar = part.substring(0, 1);
                camelCaseString = camelCaseString + part.replaceFirst(oldFirstChar, oldFirstChar.toUpperCase());
            } else {
                camelCaseString = camelCaseString + part + " ";
            }
            i++;
        }
    }
    return camelCaseString;
}

public static void main(String[] args) {
    String string = "HI_tHiS_is_SomE Statement";
    System.out.println(toCamelCase(string));
}

答案 10 :(得分:1)

你也可以试试这个:

 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;
    }

答案 11 :(得分:1)

您可以使用org.modeshape.common.text.Inflector

具体做法是:

String camelCase(String lowerCaseAndUnderscoredWord,
    boolean uppercaseFirstLetter, char... delimiterChars) 
     

默认情况下,此方法将字符串转换为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

答案 12 :(得分:0)

它会将Enum Constant转换为Camel Case。对于那些正在寻找这种功能的人来说,这会很有帮助。

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();
        }
    }

答案 13 :(得分:0)

对此的另一个解决方案可能如下。

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);
}

答案 14 :(得分:0)

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毫秒

答案 15 :(得分:0)

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;
}

答案 16 :(得分:0)

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的最简单程序。 希望它会帮助你......

答案 17 :(得分:0)

一个简单的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;
}

答案 18 :(得分:0)

Apache Commons项目现在确实具有CaseUtils类,该类具有一个toCamelCase方法,该方法完全符合OP的要求:

 CaseUtils.toCamelCase("THIS_IS_AN_EXAMPLE_STRING", true, '_');

答案 19 :(得分:-2)

Java 8用于多个字符串:

    const obj = Object.entries({ age : "1", weight : "1"})
                 .reduce((r, v) => (r[v[0]] = +v[1], r), {});

    console.log(obj);

答案 20 :(得分:-2)

    protected String toCamelCase(CaseFormat caseFormat, String... words){
        if (words.length  == 0){
          throw new IllegalArgumentException("Word list is empty!");
        }

        String firstWord = words[0];
        String [] restOfWords = Arrays.copyOfRange(words, 1, words.length);

        StringBuffer buffer = new StringBuffer();
        buffer.append(firstWord);
        Arrays.asList(restOfWords).stream().forEach(w->buffer.append("_"+ w.toUpperCase()));

        return CaseFormat.UPPER_UNDERSCORE.to(caseFormat, buffer.toString());

    }