Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return first n chars of a string

Tags:

go

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.

like image 477
ryan Avatar asked Dec 17 '25 00:12

ryan


1 Answers

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)) // 世
like image 161
KAdot Avatar answered Dec 19 '25 17:12

KAdot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!