ryan
ryan

Reputation: 1084

Return first n chars of a string

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.

Upvotes: 16

Views: 35134

Answers (4)

user2322217
user2322217

Reputation: 21

Based on the answer from @peter-willis, fmt.Sprintf("%.*s", n, s) does not require a hard-coded length.

Upvotes: 2

Peter Willis
Peter Willis

Reputation: 956

If n is known at compile time then you could use fmt.Sprintf("%.4s", "世界 Hello") to get the first 4 runes.

Upvotes: 1

Sumer
Sumer

Reputation: 2867

  college := "ARMY INSTITUTE OF TECHNOLOGY PUNE"
  fmt.Println(college)
 
  name :=  college[0:4]
  fmt.Println(name)

Upvotes: 3

KAdot
KAdot

Reputation: 2077

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)) // 世

Upvotes: 11

Related Questions