Cookies management by TermsFeed Cookie Consent

🏁 Check if a string starts with a substring in Go

introduction strings

It’s really simple to check if a given string starts with another substring in Go. In many programming languages, there is a startsWith() function to do this. In Go, we have HasPrefix() from the strings package. It returns true when a substring is the prefix of a string or false otherwise.

package main

import (
    "fmt"
    "strings"
)

const name = "GOSAMPLES"

func main() {
    fmt.Printf("GO is at the beginning of GOSAMPLES: %t\n", strings.HasPrefix(name, "GO"))
    fmt.Printf("SAMPLES is at the beginning of GOSAMPLES: %t\n", strings.HasPrefix(name, "SAMPLES"))
}

Output:

GO is at the beginning of GOSAMPLES: true
SAMPLES is at the beginning of GOSAMPLES: false

Thank you for being on our site 😊. If you like our tutorials and examples, please consider supporting us with a cup of coffee and we'll turn it into more great Go examples.

Have a great day!

Buy Me A Coffee

🍒 Concatenate strings in Go

Learn the differences between string concatenation methods
introduction strings

🖨️ Convert string to []byte or []byte to string in Go

Learn the difference between a string and a byte slice
introduction strings slice

🔟 Convert string to bool in Go

Learn how to parse a string as a bool
introduction strings bool