共計 841 個字符,預(yù)計需要花費 3 分鐘才能閱讀完成。
在 Go 語言中,可以通過以下幾種方法實現(xiàn)大小寫轉(zhuǎn)換:
- 使用
strings
包中的函數(shù):
strings.ToUpper(str)
:將字符串轉(zhuǎn)換為大寫形式。strings.ToLower(str)
:將字符串轉(zhuǎn)換為小寫形式。
- 使用
unicode
包中的函數(shù):
unicode.ToUpper(rune)
:將單個 Unicode 字符轉(zhuǎn)換為大寫形式。unicode.ToLower(rune)
:將單個 Unicode 字符轉(zhuǎn)換為小寫形式。
- 使用
bytes
包中的函數(shù):
bytes.ToUpper([]byte)
:將字節(jié)切片中的所有字符轉(zhuǎn)換為大寫形式。bytes.ToLower([]byte)
:將字節(jié)切片中的所有字符轉(zhuǎn)換為小寫形式。
下面是一些示例代碼:
package main
import (
"bytes"
"fmt"
"strings"
"unicode"
)
func main() {
str := "Hello World"
// 使用 strings 包中的函數(shù)
fmt.Println(strings.ToUpper(str)) // 輸出:HELLO WORLD
fmt.Println(strings.ToLower(str)) // 輸出:hello world
// 使用 unicode 包中的函數(shù)
fmt.Println(string(unicode.ToUpper(rune(str[0])))) // 輸出:H
fmt.Println(string(unicode.ToLower(rune(str[6])))) // 輸出:w
// 使用 bytes 包中的函數(shù)
fmt.Println(string(bytes.ToUpper([]byte(str)))) // 輸出:HELLO WORLD
fmt.Println(string(bytes.ToLower([]byte(str)))) // 輸出:hello world
}
請注意,大小寫轉(zhuǎn)換僅適用于 ASCII 字符和一些 Unicode 字符,對于其他 Unicode 字符可能無法正確轉(zhuǎn)換大小寫。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完