溫馨提示×

go語言大小寫轉(zhuǎn)換的方法有哪些

小億
189
2023-08-09 18:14:45
欄目: 編程語言

在Go語言中,可以通過以下幾種方法實現(xiàn)大小寫轉(zhuǎn)換:

  1. 使用strings包中的函數(shù):
  • strings.ToUpper(str):將字符串轉(zhuǎn)換為大寫形式。

  • strings.ToLower(str):將字符串轉(zhuǎn)換為小寫形式。

  1. 使用unicode包中的函數(shù):
  • unicode.ToUpper(rune):將單個Unicode字符轉(zhuǎn)換為大寫形式。

  • unicode.ToLower(rune):將單個Unicode字符轉(zhuǎn)換為小寫形式。

  1. 使用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)換大小寫。

0