go基础库之文本样式转换

在很多实际工作中,文本样式转换是最常用的方法,比如大小写转换,首字母大写,蛇形命名法,驼峰命名法等。

文本样式转换

Golang 版本

1.12.1

前言

在很多实际工作中,文本样式转换是最常用的方法,比如大小写转换,首字母大写,蛇形命名法,驼峰命名法等。

实现

创建文件case.go,代码如下:

package main

import (
	"fmt"
	"strings"
	"unicode"
)

const email = "ExamPle@domain.com"
const name = "isaac newton"
const upc = "upc"
const i = "i"

const snakeCase = "first_name"

func main() {

	// 为了比较用户输入,有时最好在相同的情况下比较输入
	input := "Example@domain.com"
	input = strings.ToLower(input)
	emailToCompare := strings.ToLower(email)
	matches := input == emailToCompare
	fmt.Printf("Email matches: %t\n", matches)

	upcCode := strings.ToUpper(upc)
	fmt.Println("UPPER case: " + upcCode)

	// 这个有向图有不同的大写字母和标题
	str := "dz"
	fmt.Printf("%s in upper: %s and title: %s \n", str,
		strings.ToUpper(str), strings.ToTitle(str))

	// 使用XXXSpecial功能
	title := strings.ToTitle(i)
	titleTurk := strings.ToTitleSpecial(unicode.TurkishCase, i)
	if title != titleTurk {
		fmt.Printf("ToTitle is defferent: %#U vs. %#U \n",
			title[0], []rune(titleTurk)[0])
	}

	// 在某些情况下,需要纠正输入以防万一
	correctNameCase := strings.Title(name)
	fmt.Println("Corrected name: " + correctNameCase)

	// 使用Title和ToLower函数将蛇形命名法转换为驼峰命名法
	firstNameCamel := toCamelCase(snakeCase)
	fmt.Println("Camel case: " + firstNameCamel)

}

func toCamelCase(input string) string {
	titleSpace := strings.Title(strings.Replace(input, "_", " ", -1))
	camel := strings.Replace(titleSpace, " ", "", -1)
	return strings.ToLower(camel[:1]) + camel[1:]
}
$ go run case.go
Email matches: true
UPPER case: UPC
dz in upper: DZ and title: Dz 
ToTitle is defferent: U+0049 'I' vs. U+0130 'İ' 
Corrected name: Isaac Newton
Camel case: firstName

原理

注意Unicode中的标题大小写映射与大写字母映射不同。不同之处在于字符的数量需要特殊处理。这些主要是连接符和有向图,如 fl, dz, and lj,加上一些多音体希腊字符。例如,U+01C7 (LJ)映射到U+01C8 (Lj) 而不是U+01C9 (lj)

为了正确区分大小写,应该使用string包中的EqualFold函数。这个函数使用case折叠对字符串进行规范化并比较它们。