英文:
Make first letter of string lower case in golang
问题
我想要将给定字符串的首字母小写化。我已经查看了cases和strings包,最接近的是cases.Title
。
cases.Title(language.Und, cases.NoLower).String("MyString")
这个函数可以接受第二个参数cases.someThing
,但是我找不到一种只将第一个字符小写化的方法。
PS. 使用的是Go版本1.20。
英文:
I'd like to de-capitalise the first letter of a given string. I've looked into the cases and strings packages, the closest I found was cases.Title
cases.Title(language.Und, cases.NoLower).String("MyString")
Which can take in a second argument cases.someThing
however with this, I cannot find a way need to achieve lowering just the first character.
PS. Using go version 1.20
答案1
得分: 1
在Go语言中,编写一个简单高效的函数。
package main
import (
"fmt"
"unicode"
"unicode/utf8"
)
func firstToLower(s string) string {
r, size := utf8.DecodeRuneInString(s)
if r == utf8.RuneError && size <= 1 {
return s
}
lc := unicode.ToLower(r)
if r == lc {
return s
}
return string(lc) + s[size:]
}
func main() {
fmt.Println(firstToLower("Hello World"))
fmt.Println(firstToLower("hello World"))
}
输出结果为:
hello World
hello World
英文:
In Go, write a simple and efficient function.
package main
import (
"fmt"
"unicode"
"unicode/utf8"
)
func firstToLower(s string) string {
r, size := utf8.DecodeRuneInString(s)
if r == utf8.RuneError && size <= 1 {
return s
}
lc := unicode.ToLower(r)
if r == lc {
return s
}
return string(lc) + s[size:]
}
func main() {
fmt.Println(firstToLower("Hello World"))
fmt.Println(firstToLower("hello World"))
}
https://go.dev/play/p/Vtx75XKWJsD
hello World
hello World
答案2
得分: 0
像这样吗?
https://goplay.tools/snippet/c7b_OZ19oMC
func firstLetterToLower(s string) string {
if len(s) == 0 {
return s
}
r := []rune(s)
r[0] = unicode.ToLower(r[0])
return string(r)
}
英文:
Something like this?
https://goplay.tools/snippet/c7b_OZ19oMC
func firstLetterToLower(s string) string {
if len(s) == 0 {
return s
}
r := []rune(s)
r[0] = unicode.ToLower(r[0])
return string(r)
}
答案3
得分: 0
不使用unicode
库的替代解决方案,用于ASCII拉丁字符。由于小写字符的字节值比大写字符大32,因此这应该可以工作。
package main
import (
"fmt"
)
func main() {
fmt.Println(toLowerFirstC("Hello World"))
}
func toLowerFirstC(s string) string {
if len(s) != 0 && (s[0] <= 90 && s[0] >= 65) {
return string(s[0] + 32) + string(s[1:])
}
return s
}
输出:
hello World
英文:
Alternative solution without using unicode
library for ASCII latin characters. Since byte value of lower case of these characters 32 more compared to upper case this should work.
package main
import (
"fmt"
)
func main() {
fmt.Println(toLowerFirstC("Hello World"))
}
func toLowerFirstC(s string) string {
if len(s) != 0 && (s[0] <= 90 && s[0] >= 65) {
return string(s[0] + 32) + string(s[1:])
}
return s
}
Output:
hello World
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论