go基础库之文本样式转换

栏目: Go · 发布时间: 6年前

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

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

文本样式转换

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折叠对字符串进行规范化并比较它们。


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Web界面设计

Web界面设计

Bill Scott、Theresa Neil / 李松峰 / 电子工业出版社 / 2015-3 / 108.00

当前的Web已经进入崭新的时代!《Web界面设计》涵盖了在基于独一无二的Web环境下、在创建丰富体验的过程中设计Web界面的最佳实践、模式和原理。UI专家Bill Scott和Theresa Neil在他们多年实践经验和不懈探索的基础上,总结提炼出了Web界面设 计的六大原理——直截了当、简化交互、足不出户、提供邀请、巧用变换和即时反应,并以这六大原理为依托,以当今Web上各类开风气之先的流行网站......一起来看看 《Web界面设计》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

html转js在线工具
html转js在线工具

html转js在线工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试