2 Star 2 Fork 9

王布衣/gox

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
string_snake.go 1.38 KB
一键复制 编辑 原始数据 按行查看 历史
王布衣 提交于 2021-08-23 12:30 . 增加string书写风格转换
// Copyright (c) 2017, A. Stoewer <adrian.stoewer@rz.ifi.lmu.de>
// All rights reserved.
package api
import (
"strings"
)
// SnakeCase converts a string into snake case.
func SnakeCase(s string) string {
return delimiterCase(s, '_', false)
}
// UpperSnakeCase converts a string into snake case with capital letters.
func UpperSnakeCase(s string) string {
return delimiterCase(s, '_', true)
}
// delimiterCase converts a string into snake_case or kebab-case depending on the delimiter passed
// as second argument. When upperCase is true the result will be UPPER_SNAKE_CASE or UPPER-KEBAB-CASE.
func delimiterCase(s string, delimiter rune, upperCase bool) string {
s = strings.TrimSpace(s)
buffer := make([]rune, 0, len(s)+3)
adjustCase := toLower
if upperCase {
adjustCase = toUpper
}
var prev rune
var curr rune
for _, next := range s {
if isDelimiter(curr) {
if !isDelimiter(prev) {
buffer = append(buffer, delimiter)
}
} else if isUpper(curr) {
if isLower(prev) || (isUpper(prev) && isLower(next)) {
buffer = append(buffer, delimiter)
}
buffer = append(buffer, adjustCase(curr))
} else if curr != 0 {
buffer = append(buffer, adjustCase(curr))
}
prev = curr
curr = next
}
if len(s) > 0 {
if isUpper(curr) && isLower(prev) && prev != 0 {
buffer = append(buffer, delimiter)
}
buffer = append(buffer, adjustCase(curr))
}
return string(buffer)
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/quant1x/gox.git
git@gitee.com:quant1x/gox.git
quant1x
gox
gox
v1.12.7

搜索帮助