How to check if a string starts with a substring in Golang

Last updated on Sep 11, 2022 by Suraj Sharma



In this tutorial, you will learn how you can check if a string starts with a substring in golang


The Go strings module has a HasPrefix() function that accepts two arguments, string1 and string2 to check if the first argument starts with the second argument or not, and returns a truthy value.


Example


package main

import (
    "strings"
)

func main() {
    hasPrefix := strings.HasPrefix("programming language",  "program") //true
  noPrefix := strings.HasPrefix("language",  "ang") // false
}


Related Solutions


Rate this post


Suraj Sharma is a Full Stack Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.