Is there a StartsWith(str1, str2 string)
function that can check if str1
is a prefix of str2
in Go language?
I want a function similar to the Java's startsWith()
.
In Golang strings, you can check whether the string begins with the specified prefix or not with the help of HasPrefix() function. This function returns true if the given string starts with the specified prefix and return false if the given string does not start with the specified prefix.
How to find the length of the string?: In Golang string, you can find the length of the string using two functions one is len() and another one is RuneCountInString(). The RuneCountInString() function is provided by UTF-8 package, this function returns the total number of rune presents in the string.
The strings package has what you are looking for. Specifically the HasPrefix function: http://golang.org/pkg/strings/#HasPrefix
Example:
fmt.Println(strings.HasPrefix("my string", "prefix")) // false fmt.Println(strings.HasPrefix("my string", "my")) // true
That package is full of a lot of different string helper functions you should check out.
For Example
If you want to check if a string starts with a dot
package main import "strings" func main() { str := ".com" fmt.Println(strings.HasPrefix(str, ".") }
Terminal:
$ true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With