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 983
清歌不尽
清歌不尽 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:59

    Here is a slight variation of Andreas' answer that does more than the OP asked for:

    public static String toJavaMethodName(final String nonJavaMethodName){
        final StringBuilder nameBuilder = new StringBuilder();
        boolean capitalizeNextChar = false;
        boolean first = true;
    
        for(int i = 0; i < nonJavaMethodName.length(); i++){
            final char c = nonJavaMethodName.charAt(i);
            if(!Character.isLetterOrDigit(c)){
                if(!first){
                    capitalizeNextChar = true;
                }
            } else{
                nameBuilder.append(capitalizeNextChar
                    ? Character.toUpperCase(c)
                    : Character.toLowerCase(c));
                capitalizeNextChar = false;
                first = false;
            }
        }
        return nameBuilder.toString();
    }
    

    It handles a few special cases:

    • fUnnY-cASe is converted to funnyCase
    • --dash-before-and--after- is converted to dashBeforeAndAfter
    • some.other$funky:chars? is converted to someOtherFunkyChars

提交回复
热议问题