返回前 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)) // 世
college := "ARMY INSTITUTE OF TECHNOLOGY PUNE"
fmt.Println(college)
name := college[0:4]
fmt.Println(name)
如果
n
在编译时已知,那么您可以使用 fmt.Sprintf("%.4s", "世界 Hello")
来获取前 4 个符文。