golang首字母转大小写,驼峰下划线互转

作者: adm 分类: go 发布时间: 2023-06-03
/**
     * @Author QY
     * @Email zf@zfshop.cn
     * @Description //驼峰转下划线
     * @Date 9:51 AM 6/3/23
     * @Param
     * @return
**/
func  ToSnakeCase(s string) string {
	buf := bytes.Buffer{}
	for i, r := range s {
		if unicode.IsUpper(r) {
			if i > 0 {
				buf.WriteRune('_')
			}
			buf.WriteRune(unicode.ToLower(r))
		} else {
			buf.WriteRune(r)
		}
	}
	return buf.String()
}

/**
     * @Author QY
     * @Email zf@zfshop.cn
     * @Description //下划线转驼峰
     * @Date 9:52 AM 6/3/23
     * @Param
     * @return
**/
func  ToCamelCase(s string) string {
	words := strings.Split(s, "_")
	for i := 1; i < len(words); i++ {
		words[i] = cases.Title(language.English).String(words[i])
	}
	return strings.Join(words, "")
}

/**
     * @Author QY
     * @Email zf@zfshop.cn
     * @Description //下划线转驼峰首字母大写
     * @Date 10:05 AM 6/3/23
     * @Param
     * @return
**/
func  TitleCaseToCamelCase(s string) string {
	words := ToCamelCase(s)

	return LeftUpper(words)
}

/**
     * @Author QY
     * @Email zf@zfshop.cn
     * @Description //下划线转驼峰首字母小写
     * @Date 10:05 AM 6/3/23
     * @Param
     * @return
**/
func TitleLowerToCamelCase(s string) string {
	words := ToCamelCase(s)

	return LeftLower(words)
}

// LeftUpper 首字母转大写
func LeftUpper(s string) string {
	if len(s) > 0 {
		return strings.ToUpper(string(s[0])) + s[1:]
	}
	return s
}

// LeftLower 首字母转小写
func LeftLower(s string) string {
	if len(s) > 0 {
		return strings.ToLower(string(s[0])) + s[1:]
	}
	return s
}

如果觉得我的文章对您有用,请随意赞赏。您的支持将鼓励我继续创作!