Go语言如何仅将字符串首字母转为大写 保留其余字符原有格式
Go语言实现字符串仅首个字母大写的方案
问题原因
你之前用到的两个方法不符合需求的原因如下:
strings.Title:会将字符串中所有单词的首字母全部转为大写,会把你原字符串里的ocean这类单词首字母也改大写,不符合预期strings.ToTitle:会将字符串所有字符全部转为大写,完全不匹配需求
实现方案
方案1:ASCII场景极简实现
如果确定输入字符串的首字符为单字节ASCII字符,可以用以下简单写法,性能最优:
package main import ( "fmt" "strings" ) func main() { sentence := "the biggest ocean is the Pacific ocean" // 先判空避免越界 if len(sentence) == 0 { fmt.Println(sentence) return } // 首字符转大写后拼接剩余字符串 result := strings.ToUpper(sentence[:1]) + sentence[1:] fmt.Println(result) }
运行输出:
The biggest ocean is the Pacific ocean
完全符合你的要求。
方案2:全Unicode字符兼容实现
如果输入字符串可能存在多字节的Unicode首字符(比如中文、俄文等),需要用utf8包处理避免乱码:
package main import ( "fmt" "unicode" "unicode/utf8" ) func upperFirstRune(s string) string { if s == "" { return "" } // 解码第一个Unicode字符和它的字节长度 r, size := utf8.DecodeRuneInString(s) return string(unicode.ToUpper(r)) + s[size:] } func main() { sentence := "the biggest ocean is the Pacific ocean" result := upperFirstRune(sentence) fmt.Println(result) }
这个实现兼容所有语言的字符场景,通用性更强。
内容的提问来源于stack exchange,提问作者Ineedanswers
相关产品推荐
相关产品推荐

