What is the best way to return first n chars as substring of a string, when there isn't n chars in the string, just return the string itself.
I can do the following:
func firstN(s string, n int) string {
if len(s) > n {
return s[:n]
}
return s
}
but is there a cleaner way?
BTW, in Scala, I can just do s take n.
Your code is fine unless you want to work with unicode:
fmt.Println(firstN("世界 Hello", 1)) // �
To make it work with unicode you can modify the function in the following way:
// 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)) // 世
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With