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 971
清歌不尽
清歌不尽 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:45

    If you don't like to depend on a library you can use a combination of a regex and String.format. Use a regex to extract the starting characters after the -. Use these as input for String.format. A bit tricky, but works without a (explizit) loop ;).

    public class Test {
    
        public static void main(String[] args) {
            System.out.println(convert("do-some-stuff"));
        }
    
        private static String convert(String input) {
            return String.format(input.replaceAll("\\-(.)", "%S"), input.replaceAll("[^-]*-(.)[^-]*", "$1-").split("-"));
        }
    
    }
    

提交回复
热议问题