Golang strings.HasPrefix() Function with Examples

Golang | strings.HasPrefix() Function: Here, we are going to learn about the HasPrefix() function of the strings package with its usages, syntax, and examples.
Submitted by IncludeHelp, on August 16, 2021

strings.HasPrefix()

The HasPrefix() function is an inbuilt function of strings package which is used to check whether a string begins with the given prefix. It accepts a string and prefix (substring) and returns true if the string begins with a prefix, false otherwise.

Syntax:

func HasPrefix(str, prefix string) bool

Parameter(s):

  • str: String in which we want to check the prefix.
  • prefix : Prefix to be checked

Return Value:

The return type of HasPrefix() function is a bool, it returns true if the string begins with a prefix, false otherwise.

Example 1:

// Golang program to demonstrate the
// example of strings.HasPrefix() Function

package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(strings.HasPrefix("Hello, world!", "H"))
	fmt.Println(strings.HasPrefix("__@Okay123", "__@"))
	fmt.Println(strings.HasPrefix("Hello, world", "Hi"))
}

Output:

true
true
false

Example 2:

// Golang program to demonstrate the
// example of strings.HasPrefix() Function

package main

import (
	"fmt"
	"strings"
)

func main() {
	var str string
	var prefix string

	str = "Hello, world! How are you?"
	prefix = "Hello"

	if strings.HasPrefix(str, prefix) == true {
		fmt.Printf("%q begins with %q\n", str, prefix)
	} else {
		fmt.Printf("%q does not begin with %q\n", str, prefix)
	}

	str = "Greetings from IncludeHelp.?"
	prefix = "Greetings"

	if strings.HasPrefix(str, prefix) == true {
		fmt.Printf("%q begins with %q\n", str, prefix)
	} else {
		fmt.Printf("%q does not begin with %q\n", str, prefix)
	}

	str = "Hello, world! How are you?"
	prefix = "Hi"

	if strings.HasPrefix(str, prefix) == true {
		fmt.Printf("%q begins with %q\n", str, prefix)
	} else {
		fmt.Printf("%q does not begin with %q\n", str, prefix)
	}
}

Output:

"Hello, world! How are you?" begins with "Hello"
"Greetings from IncludeHelp.?" begins with "Greetings"
"Hello, world! How are you?" does not begin with "Hi"

Golang strings Package Functions »





Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.