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 940
清歌不尽
清歌不尽 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 08:03

    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.

提交回复
热议问题