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”)?

后端 未结 11 962
清歌不尽
清歌不尽 2020-11-28 07:16

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?

11条回答
  •  孤独总比滥情好
    2020-11-28 07:47

    Why not try this:

    1. split on "-"
    2. uppercase each word, skipping the first
    3. 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 :(

    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?

    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
    }
    

提交回复
热议问题