英文:
How to capitalize the first letter of a string
问题
我有一个像这样的字符串:
var sentence string = "the biggest ocean is the Pacific ocean"
我想要能够将输入字符串中的第一个字母t
大写,使得字符串变为:
"The biggest ocean is the Pacific ocean"
在Go语言中如何实现这个功能?
我尝试使用strings.Title
和strings.ToTitle
,但它们并不符合我的要求。
英文:
I have a string like this
var sentence string = "the biggest ocean is the Pacific ocean"
I want to be able to capitalize the first letter t
in the input string, so that the string becomes
"The biggest ocean is the Pacific ocean"
How to do that in Go?
I have tried using strings.Title
and strings.ToTitle
however they don't do what I want.
答案1
得分: 5
假设您的输入字符串是有效的UTF-8编码,这个线程(Golang - ToUpper() on a single byte?)非常接近,尽管不完全是一个完美的重复。我们可以在此基础上构建一个可接受的解决方案,使用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:]...))
与字符串不同,rune切片是可变的,因此您可以用ToUpper
替换第一个rune,它将处理具有大写形式的非ASCII和/或多字节代码点(例如俄语),并保持不变那些没有大写形式的代码点(例如亚洲文字)。
**注意:**大写形式和标题形式之间有区别,这在这里有简单的解释。简而言之,像DŽ这样的双字母字符在标题形式(Dž,只有第一个字母大写)和大写形式(DŽ,两个字母都大写)之间是不同的。如果您确实需要标题形式,请使用unicode.ToTitle
。
**注意2:**在string
和[]rune
之间进行转换涉及到复制,因为您从一个不可变的字符串中获得了一个可变的切片。如果您希望在性能敏感的代码中使用它,请对您的应用程序进行性能分析。
Playground: https://go.dev/play/p/HpCBM7cRflZ
如果您有一个较大的输入字符串,完全转换为rune切片可能会变得太昂贵,您可以通过使用有限的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
英文:
Assuming that your input string is valid UTF-8, this thread (Golang - ToUpper() on a single byte?) is close enough, though not quite a perfect duplicate. We can build on that to come to an acceptable solution using unicode.ToUpper
on the first rune of the string.
r := []rune(s)
r[0] = unicode.ToUpper(r[0])
s := string(r)
Or with a "clever" one-liner:
s := string(append([]rune{unicode.ToUpper(r[0])}, r[1:]...))
Unlike strings, rune slices are not immutable, so you can replace the first rune with ToUpper
, which will take care of non-ASCII and/or multi-byte code points that do have upper cases (e.g. Russian) and leave alone those that don't (e.g. Asian scripts)
NOTE: there is a difference between UPPER case and TITLE case, which is simply explained here. In short, digraph characters like DŽ will have different title case (Dž, only first grapheme capitalized) and upper cases (DŽ, both graphemes capitalized). If you actually need titlecase, use unicode.ToTitle
.
NOTE 2: converting to/from string
to []rune
involves copying, because you get a mutable slice from an immutable string. Do profile your application if you expect to use it in performance-sensitive code.
Playground: https://go.dev/play/p/HpCBM7cRflZ
<hr>
If you have a sizeable input string where a full rune slice conversion becomes too expensive, you can work around this using a capped strings.SplitN
on some separator, essentially to extract the first word of the text and use only that in the conversion:
sep := " "
ss := strings.SplitN(s, sep, 2)
r := []rune(ss[0])
r[0] = unicode.ToUpper(r[0])
s = string(r) + sep + ss[1])
Benchmarking with a ~30K input string shows a significant difference:
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
答案2
得分: 0
实现所需结果的最简单方法是使用strings.ToUpper()
函数。参考
var input string = "the biggest ocean is the Pacific ocean"
res := strings.ToUpper(input[:1]) + input[1:]
fmt.Println(res)
或者你可以在goplayground上尝试。
英文:
The simplest way to achieve the desired result is to use strings.ToUpper()
function. Refer
var input string = "the biggest ocean is the Pacific ocean"
res := strings.ToUpper(input[:1]) + input[1:]
fmt.Println(res)
OR
You can try it on goplayground
答案3
得分: -1
获取第一个符文,将该符文转为标题大小写,并重新组装字符串:
句子 := "the biggest ocean is the Pacific ocean"
r, i := utf8.DecodeRuneInString(句子)
句子 = string(unicode.ToTitle(r)) + 句子[i:]
fmt.Println(句子)
英文:
Get the first rune, title case that rune and reassemble the string:
sentence := "the biggest ocean is the Pacific ocean"
r, i := utf8.DecodeRuneInString(sentence)
sentence = string(unicode.ToTitle(r)) + sentence[i:]
fmt.Println(sentence)
答案4
得分: -10
我为你有一个简单的解决方案。
这是我在Github上找到的一个项目的分支。
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)
}
英文:
I have simple solution for you.
Its a fork I have of someones project on Github
https://github.com/CleanMachine1/capitalise
To use it just run in a terminal:
go mod init MODULENAME
go get github.com/cleanmachine1/capitalise
then in your code you can use
package main
import ("github.com/cleanmachine1/capitalise")
func main(){
sentence = capitalise.First(sentence)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论