Camel case and snake case: Difference between revisions
Content added Content deleted
(Add Scala implementation) |
(Add Kotlin implementation) |
||
Line 1,284: | Line 1,284: | ||
spaces => spaces |
spaces => spaces |
||
</pre> |
</pre> |
||
=={{header|Kotlin}}== |
|||
{{trans|Scala}} |
|||
<syntaxhighlight lang="Kotlin"> |
|||
fun main() { |
|||
val variableNames = listOf("snakeCase", "snake_case", "variable_10_case", "variable10Case", |
|||
"ergo rE tHis", "hurry-up-joe!", "c://my-docs/happy_Flag-Day/12.doc", " spaces ") |
|||
println(" ".repeat(26) + "=== To snake_case ===") |
|||
variableNames.forEach { text -> |
|||
println("${text.padStart(34)} --> ${toSnakeCase(text)}") |
|||
} |
|||
println("\n" + " ".repeat(26) + "=== To camelCase ===") |
|||
variableNames.forEach { text -> |
|||
println("${text.padStart(34)} --> ${toCamelCase(text)}") |
|||
} |
|||
} |
|||
fun toSnakeCase(camel: String): String { |
|||
val snake = StringBuilder() |
|||
camel.trim().replace(" ", "_").replace("-", "_").forEach { ch -> |
|||
if (snake.isEmpty() || snake.last() != '_' || ch != '_') { |
|||
if (ch.isUpperCase() && snake.isNotEmpty() && snake.last() != '_') snake.append('_') |
|||
snake.append(ch.toLowerCase()) |
|||
} |
|||
} |
|||
return snake.toString() |
|||
} |
|||
fun toCamelCase(snake: String): String { |
|||
val camel = StringBuilder() |
|||
var underscore = false |
|||
snake.trim().replace(" ", "_").replace("-", "_").forEach { ch -> |
|||
if (ch == '_') { |
|||
underscore = true |
|||
} else if (underscore) { |
|||
camel.append(ch.toUpperCase()) |
|||
underscore = false |
|||
} else { |
|||
camel.append(ch) |
|||
} |
|||
} |
|||
return camel.toString() |
|||
} |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
=== To snake_case === |
|||
snakeCase --> snake_case |
|||
snake_case --> snake_case |
|||
variable_10_case --> variable_10_case |
|||
variable10Case --> variable10_case |
|||
ergo rE tHis --> ergo_r_e_t_his |
|||
hurry-up-joe! --> hurry_up_joe! |
|||
c://my-docs/happy_Flag-Day/12.doc --> c://my_docs/happy_flag_day/12.doc |
|||
spaces --> spaces |
|||
=== To camelCase === |
|||
snakeCase --> snakeCase |
|||
snake_case --> snakeCase |
|||
variable_10_case --> variable10Case |
|||
variable10Case --> variable10Case |
|||
ergo rE tHis --> ergoRETHis |
|||
hurry-up-joe! --> hurryUpJoe! |
|||
c://my-docs/happy_Flag-Day/12.doc --> c://myDocs/happyFlagDay/12.doc |
|||
spaces --> spaces |
|||
</pre> |
|||
=={{header|Lambdatalk}}== |
=={{header|Lambdatalk}}== |
||
<syntaxhighlight lang="scheme"> |
<syntaxhighlight lang="scheme"> |