1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-23 13:52:26 +08:00

Optimized: Capitalize (#4)

* Use unicode.ToUpper func to convert first letter in string to upper case
letter.

* Preallocate memory with correct length and cap because the final
  string is not changing.
This commit is contained in:
donutloop
2021-12-28 03:04:15 +01:00
committed by GitHub
parent 99faeccb05
commit 3919160e38

View File

@@ -7,6 +7,7 @@ package strutil
import ( import (
"regexp" "regexp"
"strings" "strings"
"unicode"
) )
// CamelCase covert string to camelCase string. // CamelCase covert string to camelCase string.
@@ -40,18 +41,16 @@ func Capitalize(s string) string {
return "" return ""
} }
res := "" out := make([]rune, len(s))
for i, v := range []rune(s) { for i, v := range s {
if i == 0 { if i == 0 {
if v >= 97 && v <= 122 { out[i] = unicode.ToUpper(v)
v -= 32
}
res += string(v)
} else { } else {
res += strings.ToLower(string(v)) out[i] = unicode.ToLower(v)
} }
} }
return res
return string(out)
} }
// LowerFirst converts the first character of string to lower case. // LowerFirst converts the first character of string to lower case.