Skip to content

Commit

Permalink
fix #39 and refs #1. add rules to convert strings with numbers.
Browse files Browse the repository at this point in the history
  • Loading branch information
huandu committed Aug 25, 2018
1 parent 7bb0250 commit 55ae428
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 2 deletions.
19 changes: 17 additions & 2 deletions convert.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,9 @@ func ToCamelCase(str string) string {
// "GO_PATH" => "go_path"
// "GO PATH" => "go_path" // space is converted to underscore.
// "GO-PATH" => "go_path" // hyphen is converted to underscore.
// "HTTP2XX" => "http_2xx" // insert an underscore before a number and after an alphabet.
// "http2xx" => "http_2xx"
// "HTTP20xOK" => "http_20x_ok"
func ToSnakeCase(str string) string {
if len(str) == 0 {
return ""
Expand All @@ -102,7 +105,7 @@ func ToSnakeCase(str string) string {
buf.WriteByte(byte(str[0]))

case unicode.IsUpper(r0):
if prev != '_' {
if prev != '_' && !unicode.IsNumber(prev) {
buf.WriteRune('_')
}

Expand Down Expand Up @@ -140,6 +143,12 @@ func ToSnakeCase(str string) string {
r0 = '_'

buf.WriteRune(unicode.ToLower(r1))
} else if unicode.IsNumber(r0) {
// treat a number as an upper case rune
// so that both `http2xx` and `HTTP2XX` can be converted to `http_2xx`.
buf.WriteRune(unicode.ToLower(r1))
buf.WriteRune('_')
buf.WriteRune(r0)
} else {
buf.WriteRune('_')
buf.WriteRune(unicode.ToLower(r1))
Expand All @@ -154,9 +163,15 @@ func ToSnakeCase(str string) string {

if len(str) == 0 || r0 == '_' {
buf.WriteRune(unicode.ToLower(r0))
break
}

case unicode.IsNumber(r0):
if prev != '_' && !unicode.IsNumber(prev) {
buf.WriteRune('_')
}

buf.WriteRune(r0)

default:
if r0 == ' ' || r0 == '-' {
r0 = '_'
Expand Down
5 changes: 5 additions & 0 deletions convert_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,11 @@ func TestToSnakeCase(t *testing.T) {
"HELLO____WORLD": "hello____world",
"TW": "tw",
"_C": "_c",
"http2xx": "http_2xx",
"HTTP2XX": "http_2xx",
"HTTP20xOK": "http_20x_ok",
"HTTP20XStatus": "http_20x_status",
"HTTP-20xStatus": "http_20x_status",

" sentence case ": "__sentence_case__",
" Mixed-hyphen case _and SENTENCE_case and UPPER-case": "_mixed_hyphen_case__and_sentence_case_and_upper_case",
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module github.com/huandu/xstrings

0 comments on commit 55ae428

Please sign in to comment.