[golang]golang EqualFold 字符串比较是否相等
[golang]golang EqualFold 字符串比较是否相等
EqualFold 源码
strings.EqualFold
是忽略大小写的比较,返回bool
// 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 }
示例
package main import ( "fmt" "strings" ) func main(){ fmt.Println(strings.EqualFold("GoLang","golang")) fmt.Println(strings.EqualFold("golang","GoLang")) }
输出
true true
网名:浩秦;
邮箱:root#landv.pw;
博客:landv.cnblogs.com;
只要我能控制一個國家的貨幣發行,我不在乎誰制定法律。金錢一旦作響,壞話隨之戛然而止。