Go:标准库-文本

参考:知乎
参考:Go语言标准库
参考:Go标准库

1、strings — 字符串操作

1、字符串比较

字符串大小比较:

   /* Compare 函数,用于比较两个字符串的大小,如果两个字符串相等,返回为 0。
   	* 如果 a 小于 b ,返回 -1 ,反之返回 1 。
   	* 不推荐使用这个函数,直接使用 == != > < >= <= 等一系列运算符更加直观。
   	*/
   func Compare(a, b string) int 
  

字符串相等比较:

   //   EqualFold 函数,计算 s 与 t 忽略字母大小写后是否相等。
   func EqualFold(s, t string) bool

2、是否存在某个字符

本质上他的底层实现也是通过遍历string数组去获取包含的字符串下标,如果返回正数下标则表示存在,否则表示不存在。

字符串包含:
官方注释:Contains reports whether subslice is within b.

	// 子串 substr 在 s 中,返回 true
	func Contains(s, substr string) bool

字符串包含任意:
官方注释:ContainsAny reports whether any of the UTF-8-encoded code points in chars are within b.

	// chars 中任何一个 Unicode 代码点在 s 中,返回 true
	func ContainsAny(s, chars string) bool

字符串包含rune的内容:
官方注释:ContainsRune reports whether the rune is contained in the UTF-8-encoded byte slice b.

	// Unicode 代码点 r 在 s 中,返回 true
	func ContainsRune(s string, r rune) bool

3、子串出现次数

在 Go 中,查找子串出现次数即字符串模式匹配,实现的是 Rabin-Karp 算法。

	// Count counts the number of non-overlapping instances of substr in s.
	// If substr is an empty string, Count returns 1 + the number of Unicode code points in s.
	func Count(s, sep string) int

有几个注意点:
- 当sep(匹配字符串)为时,Count 的返回值是:utf8.RuneCountInString(s) + 1,这边要注意的是中文的长度和调用计算方式
- Count 是计算子串在字符串中出现的无重叠的次数

4、字符串分割为[]string

1、用一个或多个连续的空格分隔字符串 - Fields :

Fields 用一个多个连续的空格分隔字符串 s,返回子字符串的数组(slice)。如果字符串 s 只包含空格,则返回空列表 ([]string 的长度为 0)。其中,空格的定义是 unicode.IsSpace

	// Fields splits the string s around each instance of one or more consecutive white space
	// characters, as defined by unicode.IsSpace, returning a slice of substrings of s or an
	// empty slice if s contains only white space.
	func Fields(s string) []string 

2、通过代码点进行分隔 - FieldsFunc

FieldsFunc 用这样的 Unicode 代码点 c 进行分隔:满足 f© 返回 true。该函数返回[]string。如果字符串 s 中所有的代码点 (unicode code points) 都满足 f© 或者 s 是空,则 FieldsFunc 返回空 slice。

	// FieldsFunc splits the string s at each run of Unicode code points c satisfying f(c)
	// and returns an array of slices of s. If all code points in s satisfy f(c) or the
	// string is empty, an empty slice is returned.
	// FieldsFunc makes no guarantees about the order in which it calls f(c).
	// If f does not return consistent results for a given c, FieldsFunc may crash.
	func FieldsFunc(s string, f func(rune) bool) []string

3、分隔函数 - Split

通过分隔符sep对字符串s进行切割,如果 sep 为空,相当于分成一个个的 UTF-8 字符,也就是说字符串有多少个字符就会被切割成多少个大小的string数组

	//Split slices s into all substrings separated by sep and returns a slice of the substrings between those separators.
	func Split(s, sep string) []string 

4、分隔函数控制返回个数 - SplitN

通过最后一个参数 n 控制返回的结果中的 slice 中的元素个数,当 n < 0 时,返回所有的子字符串;当 n == 0 时,返回的结果是 nil;当 n > 0 时,表示返回的 slice 中最多只有 n 个元素,其中,最后一个元素不会分割

	// The count determines the number of substrings to return:
	//   n > 0: at most n substrings; the last substring will be the unsplit remainder.
	//   n == 0: the result is nil (zero substrings)
	//   n < 0: all substrings	
	func SplitN(s, sep string, n int) []string 

5、分隔保留分隔符 - SplitAfter

SplitAfter 在分隔字符串的时候会保留 分隔符sep

	// SplitAfter slices s into all substrings after each instance of sep and
	// returns a slice of those substrings.
	func SplitAfter(s, sep string) []string

6、分隔保留分隔符控制返回个数 - SplitAfterN

通过最后一个参数 n 控制返回的结果中的 slice 中的元素个数,当 n < 0 时,返回所有的子字符串;当 n == 0 时,返回的结果是 nil;当 n > 0 时,表示返回的 slice 中最多只有 n 个元素,其中,最后一个元素不会分割

	//   n > 0: at most n substrings; the last substring will be the unsplit remainder.
	//   n == 0: the result is nil (zero substrings)
	//   n < 0: all substrings
	func SplitAfterN(s, sep string, n int) []string 

5、字符串是否有某个前缀(后缀)

1、是否有某某前缀

	// HasPrefix tests whether the string s begins with prefix.
	func HasPrefix(s, prefix string) bool 

2、是否有某某后缀

	// HasSuffix tests whether the string s ends with suffix.
	func HasSuffix(s, suffix string) bool 

6、子串在字符串中出现的位置

1、返回第一次出现的索引

	// 在 s 中查找 sep 的第一次出现,返回第一次出现的索引
	func Index(s, sep string) int
	// 在 s 中查找字节 c 的第一次出现,返回第一次出现的索引
	func IndexByte(s string, c byte) int
	// Unicode 代码点 r 在 s 中第一次出现的位置
	func IndexRune(s string, r rune) int

2、任何一个字符第一次出现的索引

	// chars 中任何一个 Unicode 代码点在 s 中首次出现的位置
	func IndexAny(s, chars string) int

3、满足条件的第一次出现的索引

	// 查找字符 c 在 s 中第一次出现的位置,其中 c 满足 f(c) 返回 true
	func IndexFunc(s string, f func(rune) bool) int

4、最后一次出现的索引(对应上面)

	// 在 s 中查找字节 c 的第一次出现,返回最后一次出现的索引
	func LastIndex(s, sep string) int
	//在 s 中查找字节 c 的第一次出现,返回最后一次出现的索引
	func LastIndexByte(s string, c byte) int
	// chars 中任何一个 Unicode 代码点在 s 中最后一次出现的位置
	func LastIndexAny(s, chars string) int
	//查找字符 c 在 s 中最后一次出现的位置,其中 c 满足 f(c) 返回 true
	func LastIndexFunc(s string, f func(rune) bool) int

7、字符串 JOIN 操作

	// Join concatenates the elements of a to create a single string. The separator string
	// sep is placed between elements in the resulting string.
	func Join(a []string, sep string) string

8、字符串重复几次

	// Repeat returns a new string consisting of count copies of the string s.
	// It panics if count is negative or if
	// the result of (len(s) * count) overflows.
	func Repeat(s string, count int) string

9、字符替换

将 s 的每一个字符按照 mapping 的规则做映射替换,如果 mapping 返回值 <0 ,则舍弃该字符。该方法只能对每一个字符做处理,但处理方式很灵活,可以方便的过滤,筛选汉字等

	// Map returns a copy of the string s with all its characters modified
	// according to the mapping function. If mapping returns a negative value, the character is
	// dropped from the string with no replacement.
	func Map(mapping func(rune) rune, s string) string 

示例:
在这里插入图片描述

10、字符串子串替换

1、控制替换的个数

	// 用 new 替换 s 中的 old,一共替换 n 个。
	// 如果 n < 0,则不限制替换次数,即全部替换
	func Replace(s, old, new string, n int) string

2、替换全部

	// 该函数内部直接调用了函数 Replace(s, old, new , -1)
	func ReplaceAll(s, old, new string) string

11、大小写转换

	//转换小写
	func ToLower(s string) string
	//转换特殊字符的小写
	func ToLowerSpecial(c unicode.SpecialCase, s string) string
	//转换大写
	func ToUpper(s string) string
	//转换特殊字符的大写
	func ToUpperSpecial(c unicode.SpecialCase, s string) string

12、标题处理

	//将s 每个单词的首字母大写
	func Title(s string) string
	//将 s 的每个字母大写
	func ToTitle(s string) string
	// 将 s 的每个字母大写,并且会将一些特殊字母转换为其对应的特殊大写字母
	func ToTitleSpecial(c unicode.SpecialCase, s string) string

13、修剪

1、常规修剪

	// 将 s 左侧和右侧中匹配 cutset 中的任一字符的字符去掉
	func Trim(s string, cutset string) string
	// 将 s 左侧的匹配 cutset 中的任一字符的字符去掉
	func TrimLeft(s string, cutset string) string
	// 将 s 右侧的匹配 cutset 中的任一字符的字符去掉
	func TrimRight(s string, cutset string) string

2、前缀后缀修剪

	// 如果 s 的前缀为 prefix 则返回去掉前缀后的 string , 否则 s 没有变化。
	func TrimPrefix(s, prefix string) string
	// 如果 s 的后缀为 suffix 则返回去掉后缀后的 string , 否则 s 没有变化。
	func TrimSuffix(s, suffix string) string
	// 将 s 左侧和右侧的间隔符去掉。常见间隔符包括:'\t', '\n', '\v', '\f', '\r', ' ', U+0085 (NEL)
	func TrimSpace(s string) string

3、将函数匹配的字符修剪掉

	// 将 s 左侧和右侧的匹配 f 的字符去掉
	func TrimFunc(s string, f func(rune) bool) string
	// 将 s 左侧的匹配 f 的字符去掉
	func TrimLeftFunc(s string, f func(rune) bool) string
	// 将 s 右侧的匹配 f 的字符去掉
	func TrimRightFunc(s string, f func(rune) bool) string

14、Replacer 类型

这是一个结构,没有导出任何字段,实例化通过 func NewReplacer(oldnew …string) *Replacer 函数进行,其中不定参数 oldnew 是 old-new 对,即进行多个替换。如果 oldnew 长度与奇数,会导致 panic.

	// NewReplacer panics if given an odd number of arguments.
	func NewReplacer(oldnew ...string) *Replacer

示例:
在这里插入图片描述


2、bytes

1、是否存在某个子 slice

	// 子 slice subslice 在 b 中,返回 true
	func Contains(b, subslice []byte) bool

2、[]byte 出现次数

	// slice sep 在 s 中出现的次数(无重叠)
	func Count(s, sep []byte) int

3、Runes 类型转换

该函数将 []byte 转换为 []rune ,适用于汉字等多字节字符

	// 将 []byte 转换为 []rune
	func Runes(s []byte) []rune

3、strconv — 字符串和基本数据类型之间转换

1、strconv 包转换错误处理

strconv 包定义了两个 error 类型的变量:ErrRange 和 ErrSyntax。其中,ErrRange 表示值超过了类型能表示的最大范围,比如将 “128” 转为 int8 就会返回这个错误;ErrSyntax 表示语法错误,比如将 “” 转为 int 类型会返回这个错误。

	func syntaxError(fn, str string) *NumError {
   		return &NumError{fn, str, ErrSyntax}
	}
	
	func rangeError(fn, str string) *NumError {
	    return &NumError{fn, str, ErrRange}
	}

2、字符串和整型之间的转换

1、字符串转换为整型

Atoi 是 ParseInt 的便捷版,内部通过调用 ParseInt(s, 10, 0) 来实现的
ParseInt 转为有符号整型
ParseUint 转为无符号整型

	//参数 base 代表字符串按照给定的进制进行解释。
	//一般的,base 的取值为 2~36,如果 base 的值为 0,则会根据字符串的前缀来确定 base 的值:"0x" 表示 16 进制;
	// "0" 表示 8 进制;否则就是 10 进制。
	//参数 bitSize 表示的是整数取值范围,或者说整数的具体类型。
	//取值 0、8、16、32 和 64 分别代表 int、int8、int16、int32 和 int64。
	func ParseInt(s string, base int, bitSize int) (i int64, err error)
	func ParseUint(s string, base int, bitSize int) (n uint64, err error)
	
	//Atoi 是 ParseInt 的便捷版,内部通过调用 ParseInt(s, 10, 0) 来实现的
	func Atoi(s string) (i int, err error)

2、整型转换为字符串

Itoa 内部直接调用 FormatInt(i, 10) 实现的。base 参数可以取 2~36(0-9,a-z)。

	//base 参数可以取 2~36(0-9,a-z)
	func FormatUint(i uint64, base int) string    // 无符号整型转字符串
	func FormatInt(i int64, base int) string    // 有符号整型转字符串
	//Itoa 内部直接调用 FormatInt(i, 10) 实现的。
	func Itoa(i int) string

3、字符串和布尔值之间的转换

	// 接受 1, t, T, TRUE, true, True, 0, f, F, FALSE, false, False 等字符串;
	// 其他形式的字符串会返回错误
	func ParseBool(str string) (value bool, err error)
	
	// 直接返回 "true" 或 "false"
	func FormatBool(b bool) string
	
	// 将 "true" 或 "false" append 到 dst 中
	// 这里用了一个 append 函数对于字符串的特殊形式:append(dst, "true"...)
	func AppendBool(dst []byte, b bool)

4、字符串和浮点数之间的转换

由于浮点数有精度的问题,精度不一样,ParseFloat 和 FormatFloat 可能达不到互逆的效果

	func ParseFloat(s string, bitSize int) (f float64, err error)
	
	//prec 表示有效数字(对 fmt='b' 无效),对于 'e', 'E' 和 'f',有效数字用于小数点之后的位数;
	//对于 'g' 和 'G',则是所有的有效数字
	func FormatFloat(f float64, fmt byte, prec, bitSize int) string
	
	func AppendFloat(dst []byte, f float64, fmt byte, prec int, bitSize int)

5、Go 语言字面值字符串输出

	strconv.Quote("studygolang.com")   //输出为 "studygolang.com"

4、Regexp - 正则表达式

参考:github

5、unicode - Unicode 码点、UTF-8/16 编码

具体示例参考:unicode

1、unicode 包

	func IsControl(r rune) bool  // 是否控制字符
	func IsDigit(r rune) bool  // 是否阿拉伯数字字符,即 0-9
	func IsGraphic(r rune) bool // 是否图形字符
	func IsLetter(r rune) bool // 是否字母
	func IsLower(r rune) bool // 是否小写字符
	func IsMark(r rune) bool // 是否符号字符
	func IsNumber(r rune) bool // 是否数字字符,比如罗马数字Ⅷ也是数字字符
	func IsOneOf(ranges []*RangeTable, r rune) bool // 是否是 RangeTable 中的一个
	func IsPrint(r rune) bool // 是否可打印字符
	func IsPunct(r rune) bool // 是否标点符号
	func IsSpace(r rune) bool // 是否空格
	func IsSymbol(r rune) bool // 是否符号字符
	func IsTitle(r rune) bool // 是否 title case
	func IsUpper(r rune) bool // 是否大写字符
	func Is(rangeTab *RangeTable, r rune) bool // r 是否为 rangeTab 类型的字符
	func In(r rune, ranges ...*RangeTable) bool  // r 是否为 ranges 中任意一个类型的字符

2、utf8 包

	//判断是否符合 utf8 编码的函数:
	func Valid(p []byte) bool
	func ValidRune(r rune) bool
	func ValidString(s string) bool
	
	//判断 rune 所占字节数:
	func RuneLen(r rune) int
	
	//判断字节串或者字符串的 rune 数:
	func RuneCount(p []byte) int
	func RuneCountInString(s string) (n int)

	//编码和解码到 rune:
	func EncodeRune(p []byte, r rune) int
	func DecodeRune(p []byte) (r rune, size int)
	func DecodeRuneInString(s string) (r rune, size int)
	func DecodeLastRune(p []byte) (r rune, size int)
	func DecodeLastRuneInString(s string) (r rune, size int)
	
	//是否为完整 rune:
	func FullRune(p []byte) bool
	func FullRuneInString(s string) bool
	
	//是否为 rune 第一个字节:
	func RuneStart(b byte) bool

3、utf16 包

将 uint16 和 rune 进行转换

	func Encode(s []rune) []uint16
	func EncodeRune(r rune) (r1, r2 rune)
	func Decode(s []uint16) []rune
	func DecodeRune(r1, r2 rune) rune
	func IsSurrogate(r rune) bool // 是否为有效代理对
发布了117 篇原创文章 · 获赞 15 · 访问量 5623

猜你喜欢

转载自blog.csdn.net/qq_34326321/article/details/104779243