'Convert kebab-case to camelCase [closed]

I'm looking for a simple return inside a method that converts any use of kebab-case and turns it into camelCase.

For example:

hello-world

Becomes

helloWorld

I'm trying to use .replaceAll() but I can't seem to get it right!



Solution 1:[1]

Just find the index of the - and then put the next char toUpperCase(), then remove the (-). You need to check if have more than one (-) and also check if the string don't have a (-) at the start of the sentence because u don't want this result:

Wrong: -hello-world => HelloWorld

Solution 2:[2]

String kebab = "hello-world";
String camel = Pattern.compile("-(.)")
    .matcher(kebab)
    .replaceAll(mr -> mr.group(1).toUpperCase());

It takes the char after the hyphen and turns it to upper-case.

Solution 3:[3]

I would use

String kebab = "hello-world";
String camel = Pattern.compile("-([a-z])")
    .matcher(kebab)
    .replaceAll(mr -> mr.group(1).toUpperCase());

You can also include a lookbehind of (?<=[a-z]) before the dash as in Pshemo's comment, if you want to only do it for dashes that come after lowercase letters instead of all instances of a dash followed by a lowercase letter, but assuming your inputs are well-formed kebab-case strings, that may not be necessary. It all depends on how you would like "-hello-world" or "HI-there" or "top10-answers" to be handled.

Solution 4:[4]

You can easily adapt these answers:

public String toCamel(String sentence) {
    sentence = sentence.toLowerCase();
    String[] words = sentence.split("-");
    String camelCase= words[0];
    for(int i=1; i<words.length; i++){
        camelCase += words[i].substring(0,1).toUpperCase() + words[i].substring(1);
    }
    return camelCase;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Alberto Linde
Solution 2 Joop Eggen
Solution 3 David Conrad
Solution 4 PaoloJ42