HasPrefix
, HasSuffix
Most languages (including Go) provide helpful methods to test the starts and ends of strings. This avoids the need for complex loops.
In Go, we have HasPrefix
and HasSuffix
. These are string
"starts with" and "ends with" methods. We can test 1 char
or more at the beginning or ending parts of a string
.
HasPrefix
exampleThis func
returns true or false. It receives two arguments: the first is the string
we are trying to test. The second is a possible "prefix" of that string
.
string
"New York" for the possible prefix "New." The HasPrefix()
func
returns true.package main import ( "fmt" "strings" ) func main() { prefix := "New " city := "New York" // See if city string begins with prefix string. if strings.HasPrefix(city, prefix) { fmt.Println(true) } }true
HasSuffix
This tests the end chars of a string
. We can test the last character with a 1-char string
—for example, we can test to see if we have a question.
package main import ( "fmt" "strings" ) func main() { value := "Is there a box?" // See if we have a question. if strings.HasSuffix(value, "?") { fmt.Println("ENDS WITH QUESTION") } }ENDS WITH QUESTION
Methods like HasPrefix
and HasSuffix
are not hard to use. But simple examples can make them easier to understand at first. They are useful in many Go programs.