Menu Close

Go – How to check if string starts with prefix in go golang

Here, We are going to learn about checking a string starts with given prefix in go golang. We can do this by using HasPrefix() function of strings package in go golang.

HasPrefix() function tests whether the string begins with prefix.

Function Prototype:

func HasPrefix(str string, prefix string) bool

Return Value:

It returns bool value. If string str begins with given prefix, then it return ‘true’ else ‘false’.

Example with code:

package main

import (
	"fmt"
	"strings"
)

func main() {

	var res bool
	
	
	res = strings.HasPrefix("Techieindoor", "Techie")

	fmt.Println(res)
	
	
	res = strings.HasPrefix("Hello Techie!", "Hello")
	
	fmt.Println(res)
	
	
	res = strings.HasPrefix("Hello Geeks", "Geeks")
	
	fmt.Println(res)
	
	
	res = strings.HasPrefix("Hello Geeks", "")
	
	fmt.Println(res)
	
}

Output:

true
true
false
true

To learn more about golang, Please refer given below link.

https://www.techieindoor.com/go-lang-tutorial/

References:

https://golang.org/doc/
https://golang.org/pkg/
Posted in golang, packages, strings

Leave a Reply

Your email address will not be published. Required fields are marked *