返回前 n 个字符作为字符串的子字符串的最佳方法是什么,当字符串中没有 n 个字符时,只需返回字符串本身。
我可以执行以下操作:
func firstN(s string, n int) string {
if len(s) > n {
return s[:n]
}
return s
}
Run Code Online (Sandbox Code Playgroud)
但有没有更干净的方法呢?
顺便说一句,在 Scala 中,我可以这样做s take n。
你的代码很好,除非你想使用 unicode:
\n\nfmt.Println(firstN("\xe4\xb8\x96\xe7\x95\x8c Hello", 1)) // \xef\xbf\xbd\nRun Code Online (Sandbox Code Playgroud)\n\n要使其与 unicode 一起使用,您可以按以下方式修改该函数:
\n\n// allocation free version\nfunc firstN(s string, n int) string {\n i := 0\n for j := range s {\n if i == n {\n return s[:j]\n }\n i++\n }\n return s\n}\nfmt.Println(firstN("\xe4\xb8\x96\xe7\x95\x8c Hello", 1)) // \xe4\xb8\x96\n\n// you can also convert a string to a slice of runes, but it will require additional memory allocations\nfunc firstN2(s string, n int) string {\n r := []rune(s)\n if len(r) > n {\n return string(r[:n])\n }\n return s\n}\nfmt.Println(firstN2("\xe4\xb8\x96\xe7\x95\x8c Hello", 1)) // \xe4\xb8\x96\nRun Code Online (Sandbox Code Playgroud)\n