Table of Contents
I wrote the code to convert string in Kotlin. This time I tried the following 4 patterns.
- Make first letter lower
- Make first letter upper
- Convert snake case string to camel case
- Convert camel case string to snake case
I published in GitHub. And you can use it in your project when you write the dependencies into your build.gradle
.
Code
Make first letter lower
1 2 3 4 5 6 7 |
fun String.beginWithLowerCase(): String { return when (this.length) { 0 -> "" 1 -> this.toLowerCase() else -> this[0].toLowerCase() + this.substring(1) } } |
We can use regular expression also.
Make first letter upper
1 2 3 4 5 6 7 |
fun String.beginWithUpperCase(): String { return when (this.length) { 0 -> "" 1 -> this.toUpperCase() else -> this[0].toUpperCase() + this.substring(1) } } |
Convert snake case string to camel case
1 2 3 4 |
fun String.toCamelCase(): String { return this.split('_').map { it.beginWithUpperCase() } .joinToString("") } |
Convert camel case string to snake case
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
fun String.toSnakeCase(): String { var text: String = "" var isFirst = true this.forEach { if (it.isUpperCase()) { if (isFirst) isFirst = false else text += "_" text += it.toLowerCase() } else { text += it } } return text } |