🏁 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

🖨️ 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

👯 Remove duplicate spaces from a string in Go

Learn how to remove all redundant whitespaces from a string
introduction strings regex