Golang 如何用小写字母转换一个字节片
在Go语言中slice比数组更强大、灵活、方便,是一种轻量级的数据结构。slice是一个可变长度的序列,它存储相似类型的元素,你不允许在同一个slice中存储不同类型的元素。
在Go的字节片中,你可以使用ToLower()函数将一个slice转换为小写。这个函数返回给定字节片的副本(视为UTF-8编码的字节),其中所有Unicode字母被映射为小写。它被定义在字节包下,因此,你必须在你的程序中导入字节包以访问ToLower函数。
语法
func ToLower(slice_1 []byte) []byte
这里,slice_1代表一个你想转换为小写字母的字节片。
例子
// Go program to illustrate how to convert
// the case of the given slice into lowercase
package main
import (
"bytes"
"fmt"
)
// Main function
func main() {
// Creating and initializing
// the slice of bytes
// Using shorthand declaration
slice_1 := []byte{'G', 'E', 'E', 'K', 'S'}
slice_2 := []byte{'A', 'P', 'P', 'L', 'E'}
//Displaying slices
fmt.Println("Original slice:")
fmt.Printf("Slice 1: %s", slice_1)
fmt.Printf("\nSlice 2: %s", slice_2)
// Converting the elements of the
// given slices into lowercase
// Using ToLower function
res1 := bytes.ToLower(slice_1)
res2 := bytes.ToLower(slice_2)
res3 := bytes.ToLower([]byte("GEEKSFORGEEKS"))
res4 := bytes.ToLower([]byte("GeeKSFORGeeKS"))
// Display the results
fmt.Printf("\n\nNew Slice:")
fmt.Printf("\nSlice 1: %s", res1)
fmt.Printf("\nSlice 2: %s", res2)
fmt.Printf("\nSlice 3: %s", res3)
fmt.Printf("\nSlice 4: %s", res4)
}
输出
Original slice:
Slice 1: GEEKS
Slice 2: APPLE
New Slice:
Slice 1: geeks
Slice 2: apple
Slice 3: geeksforgeeks
Slice 4: geeksforgeeks
极客教程