Camel case and snake case: Difference between revisions
Content added Content deleted
m (→{{header|Wren}}: Minor tidy) |
(Add Scala implementation) |
||
Line 2,099: | Line 2,099: | ||
c://my-docs/happy_Flag-Day/12.doc ==> c://my-docs/happy_Flag-Day/12.doc |
c://my-docs/happy_Flag-Day/12.doc ==> c://my-docs/happy_Flag-Day/12.doc |
||
spaces ==> spaces</pre> |
spaces ==> spaces</pre> |
||
=={{header|Scala}}== |
|||
{{trans|Java}} |
|||
<syntaxhighlight lang="Scala"> |
|||
object CamelCaseAndSnakeCase extends App { |
|||
val variableNames = List("snakeCase", "snake_case", "variable_10_case", "variable10Case", |
|||
"ergo rE tHis", "hurry-up-joe!", "c://my-docs/happy_Flag-Day/12.doc", " spaces ") |
|||
println(" " * 26 + "=== To snake_case ===") |
|||
variableNames.foreach { text => |
|||
println(f"$text%34s --> ${toSnakeCase(text)}") |
|||
} |
|||
println("\n" + " " * 26 + "=== To camelCase ===") |
|||
variableNames.foreach { text => |
|||
println(f"$text%34s --> ${toCamelCase(text)}") |
|||
} |
|||
def toSnakeCase(camel: String): String = { |
|||
val snake = new StringBuilder |
|||
camel.trim.replace(" ", "_").replace("-", "_").foreach { ch => |
|||
if (snake.isEmpty || snake.last != '_' || ch != '_') { |
|||
if (ch.isUpper && snake.nonEmpty && snake.last != '_') snake.append('_') |
|||
snake.append(ch.toLower) |
|||
} |
|||
} |
|||
snake.toString |
|||
} |
|||
def toCamelCase(snake: String): String = { |
|||
val camel = new StringBuilder |
|||
var underscore = false |
|||
snake.trim.replace(" ", "_").replace("-", "_").foreach { ch => |
|||
if (ch == '_') underscore = true |
|||
else if (underscore) { |
|||
camel.append(ch.toUpper) |
|||
underscore = false |
|||
} else camel.append(ch) |
|||
} |
|||
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|V (Vlang)}}== |
=={{header|V (Vlang)}}== |
||
{{trans|go}} |
{{trans|go}} |