我有一个类似于这样的字符串
var sentence string = "the biggest ocean is the Pacific ocean"
我希望能够将输入字符串中的首字母 t
大写,使字符串变为
"The biggest ocean is the Pacific ocean"
如何在 Go 中实现此功能?
我尝试过使用 strings.Title
和 strings.ToTitle
,但它们并不是我想要的。
我有一个类似于这样的字符串
var sentence string = "the biggest ocean is the Pacific ocean"
我希望能够将输入字符串中的首字母 t
大写,使字符串变为
"The biggest ocean is the Pacific ocean"
如何在 Go 中实现此功能?
我尝试过使用 strings.Title
和 strings.ToTitle
,但它们并不是我想要的。
unicode.ToUpper
对字符串的第一个rune进行转换。 r := []rune(s)
r[0] = unicode.ToUpper(r[0])
s := string(r)
或者用一个“聪明”的一行代码:
s := string(append([]rune{unicode.ToUpper(r[0])}, r[1:]...))
ToUpper
替换第一个rune,它将处理具有大写字母(例如俄语)和保留没有大写字母(例如亚洲文字)的非ASCII和/或多字节代码点。unicode.ToTitle
。string
到[]rune
涉及复制,因为您从不可变字符串中获得可变切片。如果您希望在性能敏感的代码中使用它,请对您的应用程序进行分析。
游乐场:https://go.dev/play/p/HpCBM7cRflZ
strings.SplitN
来解决此问题,基本上提取文本的第一个单词并仅在转换中使用该单词:sep := " "
ss := strings.SplitN(s, sep, 2)
r := []rune(ss[0])
r[0] = unicode.ToUpper(r[0])
s = string(r) + sep + ss[1])
使用约30K的输入字符串进行基准测试显示出了显著的差异:
go test -v -bench=. -benchmem
goos: darwin
goarch: arm64
pkg: example.com
BenchmarkRuneConv-10 6376 183691 ns/op 258049 B/op 3 allocs/op
BenchmarkSplitN-10 1709989 706.1 ns/op 4152 B/op 3 allocs/op
PASS
ok example.com 3.477s
实现所需的结果最简单的方法是使用strings.ToUpper()
函数。参考
var input string = "the biggest ocean is the Pacific ocean"
res := strings.ToUpper(input[:1]) + input[1:]
fmt.Println(res)
或者
你可以在goplayground上尝试它。
[]
无法处理多字节输入:https://go.dev/play/p/0-bi1WmC1AX - blackgreen获取第一个符文,将该符文转换为标题大小写并重新组合字符串:
sentence := "the biggest ocean is the Pacific ocean"
r, i := utf8.DecodeRuneInString(sentence)
sentence = string(unicode.ToTitle(r)) + sentence[i:]
fmt.Println(sentence)
我有一个简单的解决方案。
这是我在Github上fork别人项目的结果。
https://github.com/CleanMachine1/capitalise
要使用它,只需在终端中运行:
go mod init MODULENAME
go get github.com/cleanmachine1/capitalise
然后在你的代码中可以使用
package main
import ("github.com/cleanmachine1/capitalise")
func main(){
sentence = capitalise.First(sentence)
}
""
或" hello"
这样的情况会出现 panic。 因此需要一些额外的代码。func firstLetterToUppercase(s string) string { sep := " " ss := strings.SplitN(s, sep, 2) r := []rune(ss[0]) if len(r) == 0 { return s } r[0] = unicode.ToUpper(r[0]) s = string(r) if len(ss) > 1 { s += sep + ss[1] } return s }
- Pedro C. Abreu