iancoleman / strcase

A golang package for converting to snake_case or CamelCase
MIT License
1.01k stars 106 forks source link

What about numbers? #4

Closed ghost closed 6 years ago

ghost commented 6 years ago

I suggest this

(sorry, cannot get the code-presentation right)

func toCamelInitCase(s string, initCase bool) string { s = strings.Trim(s, " ") n := "" capNext := initCase for , v := range s { if v >= '0' && v <= '9' { n += string(v) } if v >= 'A' && v <= 'Z' { n += string(v) } if v >= 'a' && v <= 'z' { if capNext { n += strings.ToUpper(string(v)) } else { n += string(v) } } if v == '' || v == ' ' || v == '-' { capNext = true } else { capNext = false } } return n }

iancoleman commented 6 years ago

Thanks for this. Good idea.

Triple backticks at the top and bottom of the code block will fix the format: ```

func toCamelInitCase(s string, initCase bool) string {
    s = strings.Trim(s, " ")
    n := ""
    capNext := initCase
    for _, v := range s {
        if v >= '0' && v <= '9' {
            n += string(v)
        }
        if v >= 'A' && v <= 'Z' {
            n += string(v)
        }
        if v >= 'a' && v <= 'z' {
            if capNext {
                n += strings.ToUpper(string(v))
            } else {
                n += string(v)
            }
        }
        if v == '_'  || v == ' ' || v == '-' {
            capNext = true
        } else {
            capNext = false
        }
    }
    return n
}
ghost commented 6 years ago

;-)

iancoleman commented 6 years ago

Numbers are correctly handled as of commit https://github.com/iancoleman/strcase/commit/30c986a8faa62b02632eddaa8964ad83a212e58a (ie assume numbers should act as word boundaries). The new behaviour is:

toCamel("numbers2And55with000") gives "Numbers2And55With000"
toSnake("numbers2and55with000") gives "numbers_2_and_55_with_000"