The strings package contains HasPrefix and HasSuffix.
import "strings"
startsWith := strings.HasPrefix("prefix", "pre") // true
endsWith := strings.HasSuffix("suffix", "fix") // true
play.golang.org
If you are working with bytes, you can use these functions from the bytes package:
package main
import (
"bytes"
"fmt"
)
func main() {
fmt.Println(bytes.HasPrefix([]byte("Gopher"), []byte("Go")))
fmt.Println(bytes.HasPrefix([]byte("Gopher"), []byte("C")))
fmt.Println(bytes.HasPrefix([]byte("Gopher"), []byte("")))
}
It will be less costly than converting to string first. Useful if you are reading in from an HTTP request, or reading from a local file.
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