如何在 Go 中将字符串转换为标题大小写?


Title() 是 Go 中 strings 包中的一个内建函数,用于将字符串转换为标题大小写。它将给定字符串中每个单词的第一个字符转换为大写,并返回修改后的字符串。

语法

func Title(s string) string

其中 s 是给定的字符串。

示例 1

我们来考虑以下示例 -

package main
import (
   "fmt"
   "strings"
)
func main() {
   // Intializing the Strings
   m := "title string function"
   n := "Golang string package fUNCTION"

   // Display the Strings
   fmt.Println("String 1:", m)
   fmt.Println("String 2:", n)

   // Using the Title Function
   res1 := strings.Title(m)
   res2 := strings.Title(n)

   // Display the Title Output
   fmt.Println("\nString 1 in Title Case:", res1)
   fmt.Println("String 2 in Title Case:", res2)
}

输出

它将生成以下输出 -

String 1: title string function
String 2: Golang string package fUNCTION

String 1 in Title Case: Title String Function
String 2 in Title Case: Golang String Package FUNCTION

示例 2

我们再举另一个例子 -

package main
import (
   "fmt"
   "strings"
)
func main() {
   // Intializing the Strings
   x := "syed@123 123 cDE#456"
   y := "!hello! $$$$world###"
   
   // Display the Strings
   fmt.Println("String 1:", x)
   fmt.Println("String 2:", y)

   // Using the Title Function
   test1 := strings.Title(x)
   test2 := strings.Title(y)

   // Display the Title Output
   fmt.Println("\nString 1 in Title Case:", test1)
   fmt.Println("String 2 in Title Case:", test2)
}

输出

它将生成以下输出 -

String 1: syed@123 123 cDE#456
String 2: !hello! $$$$world###

String 1 in Title Case: Syed@123 123 CDE#456
String 2 in Title Case: !Hello! $$$$World###

更新日期: 10-Mar-2022

4K+ 查看次数

开启你的 职业

完成课程,获得认证

开始
广告
© . All rights reserved.