7
0
strcase/camel.go

80 行
2.1 KiB
Go

/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ian Coleman
2018-07-04 02:36:59 +08:00
* Copyright (c) 2018 Ma_124, <github.com/Ma124>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, Subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or Substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
2015-10-09 17:13:05 +08:00
package strcase
import (
"strings"
)
// Converts a string to CamelCase
2017-06-15 10:36:32 +08:00
func toCamelInitCase(s string, initCase bool) string {
2020-08-16 20:42:39 +08:00
if s == "" {
return s
}
if a, ok := uppercaseAcronym[s]; ok {
s = a
}
n := strings.Builder{}
n.Grow(len(s))
capNext := initCase
2020-08-16 20:42:39 +08:00
for i, v := range []byte(s) {
vIsCap := v >= 'A' && v <= 'Z'
vIsLow := v >= 'a' && v <= 'z'
if capNext {
if vIsLow {
v += 'A'
v -= 'a'
}
} else if i == 0 {
if vIsCap {
v += 'a'
v -= 'A'
}
2015-10-09 17:13:05 +08:00
}
2020-08-16 21:02:43 +08:00
if vIsCap || vIsLow {
2020-08-16 20:42:39 +08:00
n.WriteByte(v)
capNext = false
2020-08-16 21:02:43 +08:00
} else if vIsNum := v >= '0' && v <= '9'; vIsNum {
n.WriteByte(v)
capNext = true
2020-08-16 20:42:39 +08:00
} else {
capNext = v == '_' || v == ' ' || v == '-' || v == '.'
2017-11-29 08:52:26 +08:00
}
2015-10-09 17:13:05 +08:00
}
2020-08-16 20:42:39 +08:00
return n.String()
2015-10-09 17:13:05 +08:00
}
2019-04-19 15:12:49 +08:00
// ToCamel converts a string to CamelCase
func ToCamel(s string) string {
2017-11-29 09:02:53 +08:00
return toCamelInitCase(s, true)
}
2019-04-19 15:12:49 +08:00
// ToLowerCamel converts a string to lowerCamelCase
func ToLowerCamel(s string) string {
2017-11-29 09:02:53 +08:00
return toCamelInitCase(s, false)
}