这是我参与11月更文挑战的第19天,活动详情查看:2021最后一次更文挑战。
golang 字符串比较
字符串比较, 可以直接使用 ==
进行比较, 也可用用 strings.Compare
比较
go 中字符串比较有三种方式:
==
比较strings.Compare
比较strings.EquslFold
比较
1 | less复制代码 |
上述代码执行结果如下:
1 | go复制代码true |
Compare 和 EqualFold 区别
EqualFold
是比较UTF-8编码在小写的条件下是否相等,不区分大小写
1 | go复制代码// EqualFold reports whether s and t, interpreted as UTF-8 strings, // are equal under Unicode case-folding. func EqualFold(s, t string) bool |
- 要注意的是
Compare
函数是区分大小写的,==
速度执行更快
1 | go复制代码// 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
字符串比较是否相等
源码实现
1 | go复制代码// EqualFold reports whether s and t, interpreted as UTF-8 strings, |
通过源码可看到 if 'A' <= sr && sr <= 'Z' && tr == sr+'a'-'A'
可以看到不区分大小写的实现。
看个完整测试代码:
1 | go复制代码// Golang program to illustrate the |
执行结构
1 | go复制代码true |
欢迎关注工作号:程序员财富自由之路
参考资料
本文转载自: 掘金