Home
Go
strings.HasPrefix and HasSuffix
Updated Jul 4, 2023
Dot Net Perls
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 example. This 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.
Here We test the 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
A review. 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Jul 4, 2023 (grammar).
Home
Changes
© 2007-2025 Sam Allen