ADVERTISEMENT
ADVERTISEMENT

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("[email protected]", "[email protected]"))
	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 »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.