Golang 如何转换大写字母的字节片

Golang 如何转换大写字母的字节片

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

在Go的字节片中,你可以使用ToUpper()函数将一个slice转换为大写。这个函数返回给定字节片的副本(视为UTF-8编码的字节),其中所有Unicode字母被映射为大写。它被定义在字节包下,因此,你必须在你的程序中导入字节包以访问ToUpper函数。

语法

func ToUpper(slice_1 []byte) []byte

这里,slice_1代表一个你想转换为大写字母的字节片断。

例子

// Go program to illustrate how to convert the
// case of the given slice into uppercase
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 uppercase
    // Using ToUpper function
    res1 := bytes.ToUpper(slice_1)
    res2 := bytes.ToUpper(slice_2)
    res3 := bytes.ToUpper([]byte("geeksforgeeks"))
    res4 := bytes.ToUpper([]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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程