返回前 n 个字符作为字符串的子字符串的最佳方法是什么,当字符串中没有 n 个字符时,只返回字符串本身。
我可以做以下事情:
func firstN(s string, n int) string {
if len(s) > n {
return s[:n]
}
return s
}
但是有没有更简洁的方法呢?
顺便说一句,在 Scala 中,我可以做 s take n
。
最佳答案
除非您想使用 unicode,否则您的代码很好:
fmt.Println(firstN("世界 Hello", 1)) // �
要使其与 unicode 一起使用,您可以按以下方式修改函数:
// allocation free version
func firstN(s string, n int) string {
i := 0
for j := range s {
if i == n {
return s[:j]
}
i++
}
return s
}
fmt.Println(firstN("世界 Hello", 1)) // 世
// you can also convert a string to a slice of runes, but it will require additional memory allocations
func firstN2(s string, n int) string {
r := []rune(s)
if len(r) > n {
return string(r[:n])
}
return s
}
fmt.Println(firstN2("世界 Hello", 1)) // 世
关于go - 返回字符串的前 n 个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41602230/