Go 字符串比较的实现示例
字符串比较, 可以直接使用 == 进行比较, 也可用用 strings.compare 比较
go 中字符串比较有三种方式:
- == 比较
- strings.compare 比较
- strings.equslfold 比较
#### 代码示例 ```go fmt.println("go"=="go") fmt.println("go"=="go") fmt.println(strings.compare("go","go")) fmt.println(strings.compare("go","go")) fmt.println(strings.equalfold("go","go"))
上述代码执行结果如下:
true
false
-1
0
true
compare 和 equalfold 区别
equalfold 是比较utf-8编码在小写的条件下是否相等,不区分大小写
// equalfold reports whether s and t, interpreted as utf-8 strings, // are equal under unicode case-folding. func equalfold(s, t string) bool
要注意的是 compare 函数是区分大小写的, == 速度执行更快
// compare is included only for symmetry with package bytes. // it is usually clearer and always faster to use the built-in // string comparison operators ==, <, >, and so on. func compare(a, b string) int
忽略大小写比较
有时候要忽略大小写比较, 可以使用strings.equalfold 字符串比较是否相等
源码实现
// equalfold reports whether s and t, interpreted as utf-8 strings, // are equal under unicode case-folding, which is a more general // form of case-insensitivity. func equalfold(s, t string) bool { for s != "" && t != "" { // extract first rune from each string. var sr, tr rune if s[0] < utf8.runeself { sr, s = rune(s[0]), s[1:] } else { r, size := utf8.decoderuneinstring(s) sr, s = r, s[size:] } if t[0] < utf8.runeself { tr, t = rune(t[0]), t[1:] } else { r, size := utf8.decoderuneinstring(t) tr, t = r, t[size:] } // if they match, keep going; if not, return false. // easy case. if tr == sr { continue } // make sr < tr to simplify what follows. if tr < sr { tr, sr = sr, tr } // fast check for ascii. if tr < utf8.runeself { // ascii only, sr/tr must be upper/lower case if 'a' <= sr && sr <= 'z' && tr == sr+'a'-'a' { continue } return false } // general case. simplefold(x) returns the next equivalent rune > x // or wraps around to smaller values. r := unicode.simplefold(sr) for r != sr && r < tr { r = unicode.simplefold(r) } if r == tr { continue } return false } // one string is empty. are both? return s == t }
通过源码可看到 if 'a' <= sr && sr <= 'z' && tr == sr+'a'-'a' 可以看到不区分大小写的实现。
看个完整测试代码:
// golang program to illustrate the // strings.equalfold() function package main // importing fmt and strings import ( "fmt" "strings" ) // calling main method func main() { // case insensitive comparing and returns true. fmt.println(strings.equalfold("geeks", "geeks")) // case insensitive comparing and returns true. fmt.println(strings.equalfold("computerscience", "computerscience")) }
执行结构
true
true
到此这篇关于go 字符串比较的实现示例的文章就介绍到这了,更多相关go 字符串比较内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
上一篇: Unity脚本自动添加头部注释的全过程
下一篇: 年夜饭的寓意和由来