Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a camel case string to snake case and back in idiomatic Kotlin?

Looking for code that will do conversions like this: "MyCamelCaseA" to "my_camel_case_a" "AMultiWordString" to "a_multi_word_string" "my_camel_case_a" to "myCamelCaseA" or "MyCamelCaseA" "a_multi_word_string" to "aMultiWordString" or "AMultiWordString"

like image 666
TER Avatar asked Jan 31 '20 19:01

TER


People also ask

How do you convert the string from camel case to snake case in python?

First, we initialize a variable 'res' with an empty list and append first character (in lower case) to it. Now, Each time we encounter a Capital alphabet, we append '_' and the alphabet (in lower case) to 'res', otherwise, just append the alphabet only.


2 Answers

Here are extensions to the String class that use regex and replacements to convert a string from camel case to snake case, and from snake case to camel case:

val camelRegex = "(?<=[a-zA-Z])[A-Z]".toRegex()
val snakeRegex = "_[a-zA-Z]".toRegex()

// String extensions
fun String.camelToSnakeCase(): String {
    return camelRegex.replace(this) {
        "_${it.value}"
    }.toLowerCase()
}

fun String.snakeToLowerCamelCase(): String {
    return snakeRegex.replace(this) {
        it.value.replace("_","")
            .toUpperCase()
    }
}

fun String.snakeToUpperCamelCase(): String {
    return this.snakeToLowerCamelCase().capitalize()
}

Here are examples using the String extension:

print("${"MyCamelCaseA".camelToSnakeCase()}\n")
my_camel_case_a
print("${"AMultiWordString".camelToSnakeCase()}\n")
a_multi_word_string
"my_camel_case_a".snakeToLowerCamelCase()
myCamelCaseA
"my_camel_case_a".snakeToUpperCamelCase()
MyCamelCaseA
like image 180
TER Avatar answered Oct 27 '22 01:10

TER


I would go with these implementations:

fun String.toCamelCase() = 
    split('_').joinToString("", transform = String::capitalize)

... which splits the string using snakes as delimiters, and then reattaches the parts as capitalized words without a delimiter.

fun String.toSnakeCase() = replace(humps, "_").toLowerCase()
private val humps = "(?<=.)(?=\\p{Upper})".toRegex()

... which uses a regex to find the positions before humps, inserting snakes, and then converts the whole string to lowercase. The regex consists of two parts, the first one (?<=.) is a positive look-behind saying that it must be preceded by a character, and the second part (?=\\p{Upper}) is using a positive look-ahead saying it must be followed by an uppercase character.

like image 20
Per Huss Avatar answered Oct 27 '22 01:10

Per Huss