Home
Map
strings.HasPrefix and HasSuffixCall HasPrefix and HasSuffix, part of the strings package, to test starts and ends of strings.
Go
This page was last reviewed on Jul 4, 2023.
HasPrefix, HasSuffix. Most languages (including Go) provide helpful methods to test the starts and ends of strings. This avoids the need for complex loops.
For Golang, 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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jul 4, 2023 (grammar).
Home
Changes
© 2007-2024 Sam Allen.