Camel case and snake case: Difference between revisions
Content added Content deleted
(Nim solution) |
|||
Line 1,101: | Line 1,101: | ||
* We don't handle consecutive upper case characters (e.g. "newUIBox"). |
* We don't handle consecutive upper case characters (e.g. "newUIBox"). |
||
* We don't handle non-ASCII characters because of Lua's limited support for them ("ɛ" just happen to work here). |
* We don't handle non-ASCII characters because of Lua's limited support for them ("ɛ" just happen to work here). |
||
=={{header|Nim}}== |
|||
We use the same rules as those used by Wren's solution. |
|||
<syntaxhighlight lang=Nim>import std/[strformat, strutils, unicode] |
|||
const Delimiters = [Rune('_'), Rune('-'), Rune(' ')] |
|||
func toCamelCase(s: string): string = |
|||
let s = s.strip(chars = Whitespace) |
|||
var prev = Rune(0) |
|||
for rune in s.runes: |
|||
if prev in Delimiters: |
|||
result.add rune.toUpper |
|||
elif rune notin Delimiters: |
|||
result.add rune |
|||
prev = rune |
|||
func toSnakeCase(s: string): string = |
|||
var s= s.strip(chars = Whitespace).replace(' ', '_') |
|||
var idx = 0 |
|||
var prev = Rune(0) |
|||
for rune in s.runes: |
|||
if rune.isUpper and idx > 0: |
|||
if prev notin Delimiters: |
|||
result.add '_' |
|||
result.add rune.toLower |
|||
else: |
|||
result.add rune |
|||
prev = rune |
|||
inc idx |
|||
const Strings = ["snakeCase", "snake_case", "variable_10_case", |
|||
"variable10Case", "ɛrgo rE tHis", "hurry-up-joe!", |
|||
"c://my-docs/happy_Flag-Day/12.doc", " spaces "] |
|||
echo center("### To snake case ###", 69) |
|||
for s in Strings: |
|||
echo &"{s:>33} → {s.toSnakeCase}" |
|||
echo() |
|||
echo center("### To camel case ###", 69) |
|||
for s in Strings: |
|||
echo &"{s:>33} → {s.toCamelCase}" |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> ### To snake case ### |
|||
snakeCase → snake_case |
|||
snake_case → snake_case |
|||
variable_10_case → variable_10_case |
|||
variable10Case → variable10_case |
|||
ɛrgo rE tHis → ɛrgo_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 camel case ### |
|||
snakeCase → snakeCase |
|||
snake_case → snakeCase |
|||
variable_10_case → variable10Case |
|||
variable10Case → variable10Case |
|||
ɛrgo rE tHis → ɛrgoRETHis |
|||
hurry-up-joe! → hurryUpJoe! |
|||
c://my-docs/happy_Flag-Day/12.doc → c://myDocs/happyFlagDay/12.doc |
|||
spaces → spaces |
|||
</pre> |
|||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
<syntaxhighlight lang="perl">#!/usr/bin/perl |
<syntaxhighlight lang="perl">#!/usr/bin/perl |