内容简介:在很多实际工作中,文本样式转换是最常用的方法,比如大小写转换,首字母大写,蛇形命名法,驼峰命名法等。
在很多实际工作中,文本样式转换是最常用的方法,比如大小写转换,首字母大写,蛇形命名法,驼峰命名法等。
文本样式转换
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折叠对字符串进行规范化并比较它们。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Practical Algorithms for Programmers
Andrew Binstock、John Rex / Addison-Wesley Professional / 1995-06-29 / USD 39.99
Most algorithm books today are either academic textbooks or rehashes of the same tired set of algorithms. Practical Algorithms for Programmers is the first book to give complete code implementations o......一起来看看 《Practical Algorithms for Programmers》 这本书的介绍吧!