golang

Golang String Starts with

In go, a string is defined as a slice of bytes. We can also define strings as a sequence of variable-width characters where each character is represented by one or more bytes. In Go, strings are immutable and occupy less memory as Go uses the UTF-8 standard.

With strings being one of the basic types, learning how to perform various operations becomes essential.

In this guide, you will learn how to check if a string begins with a specified substring or prefix or not.

Strings. HasPrefix()

To check if a string begins with a specific substring, we will use the HasPrefix() method from the strings package.

You will need to import the strings package, as shown in the example import clause below:

import "strings"

Once imported, you can use the methods from the package.

The syntax for the HasPrefix() method is as shown:

func HasPrefix(str,  substring) bool

The function takes the string and the substring to check as the parameters. The function returns a Boolean true if the string begins with the specified substring. Otherwise, the function returns a Boolean false.

To better understand how the function works, consider the example below:

package main
import (
    "fmt"
    "strings"
)

func main() {
    str_1 := "Hello everyone and welcome to Linuxhint"
    str_2 := "Here, you can learn everything tech related."
    my_prefix := " "
    // check if string starts with a specified prefix
    fmt.Println(strings.HasPrefix(str_1, "Hello"))
    fmt.Println(strings.HasPrefix(str_2, "Hello"))
    fmt.Println(strings.HasPrefix(str_2, "Here"))
    fmt.Println(strings.HasPrefix(str_1, "Linuxhint"))
    fmt.Println(strings.HasPrefix(str_2, my_prefix))
    fmt.Println(strings.HasPrefix(str_1, " "))
}

The example above tests if the strings start with a specified prefix. As you will see, you can specify the prefix value as a string literal or as a variable.

The resulting output is as shown:

true
false
true
false
false
false

Closing

This guide shows you how to use the strings. HasPrefix() method checks if a string starts with a specified substring.

Thanks for reading!

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list