Golang 如何转换字节的片断的标题情况

Golang 如何转换字节的片断的标题情况

在Go语言中slice比数组更强大、灵活、方便,是一种轻量级的数据结构。slice是一个可变长度的序列,它可以存储相似类型的元素,你不允许在同一个slice中存储不同类型的元素。
在Go的字节片中,你可以使用ToTitle()函数将一个slice转换为标题大小写。这个函数返回给定字节片的副本(视为UTF-8编码的字节),其中所有的Unicode字母都被映射到它们的标题大小写。它被定义在字节包下,因此,你必须在你的程序中导入字节包以访问ToTitle函数。

语法

func ToTitle(slice_1 []byte) []byte

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

例子

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

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程