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.
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.
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
You can use toCamelCase
util:
CaseUtils.toCamelCase("camel_case", false, new char[]{'_'}); // returns "camelCase"
from Apache Commons Text.
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);
}
}
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
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
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)
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
import org.apache.commons.lang3.text.WordUtils;
public String snakeToCamelCase(String snakeWord) {
String camelWord = snakeWord.replaceAll("_", " ");
camelWord = WordUtils.capitalizeFully(camelWord);
return camelWord.replaceAll(" ", "");
}
/**
* 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++));
}
}
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