Return first n chars of a string

go
10,216

Solution 1

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

Solution 2

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

Related videos on Youtube

ryan
Author by

ryan

Updated on June 04, 2022

Comments

  • ryan
    ryan over 1 year

    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.

    • JimB
      JimB almost 7 years
      No, Go is not Scala. How is s take n "cleaner" than firstN(s, n)?
    • Cerise Limón
      Cerise Limón almost 7 years
      When you say char, do you mean byte or rune? The code in the question looks good to me if the goal is to return the first N bytes. A loop is required to return the first N runes.
  • Maria Efimenko
    Maria Efimenko over 2 years
    I wouldn't do that if I were you) if college consisted of 2 symbols, your code would panic.
  • Sumer
    Sumer over 2 years
    Agree @MariaEfimenko , better to put checks comparing length of string and max bound