How to Remove the First Character of a String in Go

Created
Modified

Using DecodeRuneInString Function

The following example should cover whatever you are trying to do:

package main

import (
  "fmt"
  "unicode/utf8"
)

func trimFirstRune(s string) string {
  _, i := utf8.DecodeRuneInString(s)
  return s[i:]
}

func main() {
  fmt.Println(trimFirstRune("Hello"))
  fmt.Println(trimFirstRune("世界"))
}
ello
界

Using Range

You can use range to get the size of the first rune and then slice:

package main

import "fmt"

func trimFirstRune(s string) string {
  for i := range s {
    if i > 0 {
      return s[i:]
    }
  }
  return ""
}

func main() {
  fmt.Println(trimFirstRune("Hello"))
  fmt.Println(trimFirstRune("世界"))
}
ello
界

Related Tags