go starts with
To check if a string starts with a specific substring in Go, you can use the strings.HasPrefix()
function. This function returns a boolean value indicating whether the given string starts with the specified prefix.
Here is an example code snippet that demonstrates how to use strings.HasPrefix()
to check if a string starts with a specific substring:
package main
import (
"fmt"
"strings"
)
func main() {
str := "Hello, world!"
prefix := "Hello"
if strings.HasPrefix(str, prefix) {
fmt.Printf("The string '%s' starts with '%s'\n", str, prefix)
} else {
fmt.Printf("The string '%s' does not start with '%s'\n", str, prefix)
}
}
In this example, we have a string str
that contains the value "Hello, world!" and a prefix prefix
that contains the value "Hello". We use the strings.HasPrefix()
function to check if str
starts with prefix
. If it does, we print a message indicating that the string starts with the prefix. If it doesn't, we print a message indicating that the string does not start with the prefix.
When you run this code, the output will be:
The string 'Hello, world!' starts with 'Hello'
You can modify the values of str
and prefix
to test different scenarios and see the result.