How to Check If a String Starts With ...

· 139 words · 1 minute read

In this post we look at how to check if a given string starts with something. This is often used in programming and there are different ways to achieve the same goal.

We provide two options in this example. The first is to use the strings package along with the HasPrefix function - this is probably the simplest/best solution. We did include a second option though, if you know how long the prefix that you’re looking for is, you can use the string as a slice and check it’s value.

package main

import (
    "fmt"
    "strings"
)

func main() {

    myString := "Hello golangcode.com"

    // Option 1: (Recommended)
    if strings.HasPrefix(myString, "Hello") {
        fmt.Println("Hello to you too")
    } else {
        fmt.Println("Goodbye")
    }

    // Option 2:
    if len(myString) > 6 && myString[:5] == "Hello" {
        fmt.Println("Option 2 also matches")
    }
}

check if a string starts with a value

Image of Author Edd Turtle

Author:  Edd Turtle

Edd is the Lead Developer at Hoowla, a prop-tech startup, where he spends much of his time working on production-ready Go and PHP code. He loves coding, but also enjoys cycling and camping in his spare time.

See something which isn't right? You can contribute to this page on GitHub or just let us know in the comments below - Thanks for reading!