Golang 如何检查Unicode大小写折叠下的字符串是否相等
在Go语言中,字符串与其他语言如Java、C++、Python等不同。
在Go语言的字符串中,你可以在EqualFold()函数的帮助下,将两个字符串相互比较,即使它们以不同的大小写(小写和大写)书写,也不会有任何错误。或者换句话说,这个函数用来检查指定的字符串是否被解释为UTF-8字符串,以及在Unicode大小写折叠下是否相等。如果给定的字符串在Unicode大小写折叠下相等,则该函数返回true;如果给定的字符串在Unicode大小写折叠下不相等,则返回false。它被定义在strings包中,因此,你必须在你的程序中导入strings包以访问EqualFold函数。
语法
func EqualFold(str1, str2 string) bool
这个函数的返回类型是bool类型。让我们借助于例子来讨论这个概念。
例1 :
// Go program to illustrate how to
// check the given strings are equal or not
package main
import (
"fmt"
"strings"
)
// Main function
func main() {
// Creating strings
// Using var keyword
var username string
var uinput string
// Initializing strings
username = "AnkitaSaini"
uinput = "ankitasaINI"
// Checking whether the given
// strings are equal or not
// Using EqualFold() function
res := strings.EqualFold(username, uinput)
// Displaying the result according
// to the given condition
if res == true {
fmt.Println("!..Successfully Matched..!")
} else {
fmt.Println("!..Not Matched..!")
}
}
输出
!..Successfully Matched..!
例2 :
// Go program to illustrate how to check
// the given strings are equal or not
package main
import (
"fmt"
"strings"
)
// Main function
func main() {
// Creating and initializing strings
// Using shorthand declaration
s1 := "I am working as a Technical content writer, in GeeksforGeeks!"
s2 := "I am currently writing articles on Go language!"
// Checking the given strings are equal or not
// Using EqualFold() function
res1 := strings.EqualFold(s1, "I AM WORKING AS A TECHNICAL CONTENT WRITER, IN GEEKSFORGEEKS!")
res2 := strings.EqualFold(s1, "I AM working AS A Technical CONTENT writer, IN GeeksforGeeks!")
res3 := strings.EqualFold(s1, "Apple")
res4 := strings.EqualFold(s2, "I am currently writing articles on Go language!")
res5 := strings.EqualFold(s2, "I am currently writing ARTICLES on Go language!")
res6 := strings.EqualFold("GeeksforGeeks", "geeksForgeeks")
// Displaying results
fmt.Println("Result 1: ", res1)
fmt.Println("Result 2: ", res2)
fmt.Println("Result 3: ", res3)
fmt.Println("Result 4: ", res4)
fmt.Println("Result 5: ", res5)
fmt.Println("Result 6: ", res6)
}
输出
Result 1: true
Result 2: true
Result 3: false
Result 4: true
Result 5: true
Result 6: true
极客教程