📌  相关文章
📜  在 Golang 中的 Unicode 大小写折叠下检查字节片是否相等

📅  最后修改于: 2021-10-24 13:20:05             🧑  作者: Mango

在 Go 语言中切片比数组更强大、灵活、方便,是一种轻量级的数据结构。切片是一个可变长度的序列,用于存储相似类型的元素,不允许在同一个切片中存储不同类型的元素。
在 Go 字节切片中,即使在EqualFold ()函数的帮助下,这些切片的元素以不同的大小写(小写和大写)写入,您也可以将两个切片相互比较而不会出现任何错误。或者,这个函数用于检查指定的切片是否被解释为 UTF-8字符串,并且在 Unicode 大小写折叠下是否相等。如果给定的切片在 Unicode 大小写折叠下相等,则此函数返回 true;如果给定的切片在 Unicode 大小写折叠下不相等,则返回 false。它是在 bytes 包下定义的,因此您必须在程序中导入 bytes 包才能访问 EqualFold函数。

句法:

func EqualFold(slice_1, slice1_2 []byte) bool

此函数的返回类型为 bool 类型。让我们在示例的帮助下讨论这个概念:

示例 1:

// Go program to illustrate how to check
// the given slices are equal or not
package main
  
import (
    "bytes"
    "fmt"
)
  
// Main function
func main() {
  
    // Creating and initializing slices of bytes
    // Using shorthand declaration
    username := []byte{'G', 'E', 'E', 'K', 'S'}
    uinput := []byte{'g', 'e', 'e', 'k', 's'}
  
    // Checking whether the given slices are equal or not
    // Using EqualFold() function
    res := bytes.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 slices are equal or not
package main
  
import (
    "bytes"
    "fmt"
)
  
func main() {
  
    // Creating and initializing slices of bytes
    // Using shorthand declaration
    slice_1 := []byte{'G', 'E', 'E', 'K', 'S', 'F',
             'o', 'r', 'G', 'E', 'E', 'K', 'S'}
  
    slice_2 := []byte{'g', 'e', 'e', 'k', 's', 'f',
             'o', 'r', 'g', 'e', 'e', 'k', 's'}
  
    slice_3 := []byte{'A', 'P', 'P', 'L', 'E'}
  
    // Checking whether the given
    // slices are equal or not
    // Using EqualFold() function
    res1 := bytes.EqualFold(slice_1, slice_2)
    res2 := bytes.EqualFold(slice_2, slice_3)
    res3 := bytes.EqualFold(slice_3, []byte("apple"))
    res4 := bytes.EqualFold([]byte("Geeks"), []byte("GEEks"))
  
    // Displaying results
    fmt.Println("Result_1: ", res1)
    fmt.Println("Result_2: ", res2)
    fmt.Println("Result_3: ", res3)
    fmt.Println("Result_4: ", res4)
  
}

输出:

Result_1:  true
Result_2:  false
Result_3:  true
Result_4:  true