Golang 检查字节片在Unicode大小写折叠下是否相等

Golang 检查字节片在Unicode大小写折叠下是否相等

在Go语言中slice比数组更强大、灵活、方便,是一种轻量级的数据结构。slice是一个可变长度的序列,它存储相似类型的元素,你不允许在同一个slice中存储不同类型的元素。

在Go的字节slice中,你可以在 EqualFold ()函数的帮助下,将两个slice相互比较而不出错,即使这些slice的元素是以不同的大小写(小写和大写)书写。或者换句话说,这个函数用来检查指定的片断是否被解释为UTF-8字符串,以及在Unicode大小写折叠下是否相等。如果给定的片断在Unicode大小写折叠下是相等的,该函数返回true;如果给定的片断在Unicode大小写折叠下不相等,则返回false。它被定义在字节包中,因此,你必须在你的程序中导入字节包以访问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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程