21

Can anyone tell me how to convert a string in snake_case as:

camel_case

to a string in camelCase as:

camelCase

in Java?

Thank you in advance.

Max Vollmer
  • 8,412
  • 9
  • 28
  • 43
Domenico
  • 231
  • 1
  • 2
  • 6
  • What have you tried so far? Are you having problems with code you've written or are we to undertake the entire task for you? – jbowman Dec 11 '15 at 17:20
  • 2
    Read the doc! This is a simple problem any programming language should be able to do. I'm not familiar with Java but here is the pseudocode you might want to run by: 1. Loop through all characters in the string 2. If "_" is found, remove it 3. Capitalize the next character 4. Return the new string – Pandemonium Dec 11 '15 at 17:22
  • 1
    You can split the string with _ and then use StringUtils.join after capitalizing the first char of all (except first) splitted string parts – achin Dec 11 '15 at 17:23

10 Answers10

30

Also Guava's CaseFormat offers quite a neat solution that allows you to transform from and to camel case and even other specific cases.

CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, "camel_case"); // returns camelCase
CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, "CAMEL_CASE"); // returns CamelCase
CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, "camelCase"); // returns CAMEL_CASE
CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, "CamelCase"); // returns camel-case
Alex
  • 1,126
  • 1
  • 11
  • 24
  • `CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, "camelCase");` will return "camelcase", this may not be expected – kai Feb 17 '22 at 07:47
  • Why not? `LOWER_UNDERSCORE` would be a format like `camel_case`, i. e. only an underscore character breaks a word. The string `"camelCase"` is in this sense only one word and if you consequentially convert a one word string to `LOWER_CAMEL`, you will get everything in lower case. – Alex May 18 '22 at 14:36
14

You can use toCamelCase util:

CaseUtils.toCamelCase("camel_case", false, new char[]{'_'}); // returns "camelCase"

from Apache Commons Text.

Community
  • 1
  • 1
Luís Soares
  • 5,726
  • 4
  • 39
  • 66
8

This might be pretty, and it works

public class Test {

    public static void main(String[] args) {
        String phrase = "always_use_camel_back_notation_in_java";
        while(phrase.contains("_")) {
                phrase = phrase.replaceFirst("_[a-z]", String.valueOf(Character.toUpperCase(phrase.charAt(phrase.indexOf("_") + 1))));
            }
            System.out.println(phrase);
        }
    }
Roee Gavirel
  • 18,955
  • 12
  • 67
  • 94
Sher Alam
  • 372
  • 2
  • 9
  • This doesn't work for me. `Character.toUpper` is not a method and the second parameter to `String.replace` needs to be a String. I think you meant `replaceAll`? But even then, calling `indexOf("_")` will always return the first `_` because the underscores aren't iteratively replaced – OneCricketeer Dec 11 '15 at 18:58
  • My apologies. I was on another system without Eclipse. Now check my updated and verified answer. – Sher Alam Dec 11 '15 at 19:31
  • It only works for phrases with one or no underscores such as "camel_case". It still will not work for "camel_case_test". That will return "camelCaseCest" since `indexOf("_")` returns the underscore before "case". – OneCricketeer Dec 11 '15 at 19:58
  • 1
    Please check my updated answer. Now it will convert any length string to camel back notation. The while loop takes care of it. – Sher Alam Dec 11 '15 at 20:20
  • Yup. Works now. However, (I know it isn't a concern here), the runtime complexity is high with this approach. – OneCricketeer Dec 11 '15 at 20:30
  • This may loop forever if the string contains things like `permit_2pc`. Might be better to modify it with `phrase.charAt(pos = (phrase.indexOf("_", pos) + 1))` (And likewise adjust the loop condition to `s.substring(pos).contains("_")` or similar - I haven't tested this) – Caesar Nov 11 '20 at 08:36
6

This isn't pretty, but it works:

String phrase = "camel_case";
String[] words = phrase.split("_");
String newPhrase = words[0];
for(int i=1; i<words.length; i++){
  newPhrase += words[i].substring(0,1).toUpperCase() + words[i].substring(1);
}
pdem
  • 3,880
  • 1
  • 24
  • 38
hallgren
  • 61
  • 1
5

Java SE 8+

Using Java-8 Stream API, we can do it in a single statement.

import java.util.Arrays;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        String str = "snake_case_to_camel_case";

        str = str.indexOf("_") != -1
                ? str.substring(0, str.indexOf("_")) + 
                    Arrays.stream(str.substring(str.indexOf("_") + 1).split("_"))
                        .map(s -> Character.toUpperCase(s.charAt(0)) + s.substring(1)).collect(Collectors.joining())
                : str;

        System.out.println(str);
    }
}

Output:

snakeCaseToCamelCase

ONLINE DEMO

Java SE 9+

Matcher#replaceAll​(Function<MatchResult, String> replacer) introduced with Java SE 9, makes it further easy.

import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) {
        String str = "snake_case_to_camel_case";

        str = Pattern.compile("_([a-z])")
                    .matcher(str)
                    .replaceAll(m -> m.group(1).toUpperCase());

        System.out.println(str);
    }
}

Output:

snakeCaseToCamelCase

ONLINE DEMO

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
3

Take a look at oracle's documentation for the string class, notably substring, charAt, indexOf, and toUpperCase

(You can use these as puzzle pieces to solve your problem)

Noam Hacker
  • 4,671
  • 7
  • 34
  • 55
3

Using split("_") and looping over those parts is one way to do it.

Here is an alternative using a StringBuilder.

String s = "make_me_camel_case";
StringBuilder sb = new StringBuilder(s);

for (int i = 0; i < sb.length(); i++) {
    if (sb.charAt(i) == '_') {
        sb.deleteCharAt(i);
        sb.replace(i, i+1, String.valueOf(Character.toUpperCase(sb.charAt(i))));
    }
}

System.out.println(sb.toString()); // makeMeCamelCase
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
0
import org.apache.commons.lang3.text.WordUtils;

public String snakeToCamelCase(String snakeWord) {
    String camelWord = snakeWord.replaceAll("_", " ");
    camelWord = WordUtils.capitalizeFully(camelWord);
    return camelWord.replaceAll(" ", "");
}
0
/**
 * Converts AlphaNumeric String to camelcase based on any non AlphaNumeric char as delimiter
 * @param input
 * @return camelCase String
 */
public static String toCamelCase(String input) {

    StringBuilder result = new StringBuilder(input.length());
    boolean toUpper = false;
    for (int i = 0; i < input.length(); i++) {

        if (Character.isAlphabetic(input.charAt(i))) {

            if (toUpper) {

                result.append(Character.toUpperCase(input.charAt(i)));
                toUpper = false;
            } else {

                result.append(Character.toLowerCase(input.charAt(i)));
            }
        } else if (Character.isDigit(input.charAt(i))){

            result.append(input.charAt(i));
        } else {

            toUpper = true;
        }
    }
    return result.toString();
}

@Test
public void toCamelCaseTest() {

    List<String> inputs = List.of("Hello World", "helloWorld",
            "Hello_World", "helloWorld",
            "Hello-World", "helloWorld",
            "HELLO WORLD", "helloWorld",
            "HELlo_WORld", "helloWorld",
            "Hello1world", "hello1world",
            "2Hello world", "2helloWorld"
    );
    for (int i = 0; i < inputs.size();) {
        Truth.assertThat(StringUtils.toCamelCase(inputs.get(i++)))
                .isEqualTo(inputs.get(i++));
    }
}
Kanagavelu Sugumar
  • 18,766
  • 20
  • 94
  • 101
0

This task can be done with the String.split method, and a for-loop.

String convert(String string) {
    String[] strings = string.split("_+");
    StringBuilder converted = new StringBuilder();
    String stringA, stringB;
    for (String value : strings) {
        if (converted.isEmpty()) {
            if (!value.isEmpty()) converted.append(value.toLowerCase());
        } else {
            stringA = value.substring(0, 1).toUpperCase();
            stringB = value.substring(1).toLowerCase();
            converted.append(stringA).append(stringB);
        }
    }
    return converted.toString();
}

Input

convert_snake_case_to_camel_case

Output

convertSnakeCaseToCamelCase
Reilas
  • 3,297
  • 2
  • 4
  • 17