您好,登錄后才能下訂單哦!
這篇“Go如何實現字符串比較”文章,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要參考一下,對于“Go如何實現字符串比較”,小編整理了以下知識點,請大家跟著小編的步伐一步一步的慢慢理解,接下來就讓我們進入主題吧。
#### 代碼示例 ```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
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如何實現字符串比較”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。