Go Standard Library Cookbook
上QQ阅读APP看书,第一时间看更新

How to do it...

  1. Open the console and create the folder chapter02/recipe01.
  2. Navigate to the directory.
  3. Create the contains.go file with the following content:
        package main

import (
"fmt"
"strings"
)

const refString = "Mary had a little lamb"

func main() {

lookFor := "lamb"
contain := strings.Contains(refString, lookFor)
fmt.Printf("The \"%s\" contains \"%s\": %t \n", refString,
lookFor, contain)

lookFor = "wolf"
contain = strings.Contains(refString, lookFor)
fmt.Printf("The \"%s\" contains \"%s\": %t \n", refString,
lookFor, contain)

startsWith := "Mary"
starts := strings.HasPrefix(refString, startsWith)
fmt.Printf("The \"%s\" starts with \"%s\": %t \n", refString,
startsWith, starts)

endWith := "lamb"
ends := strings.HasSuffix(refString, endWith)
fmt.Printf("The \"%s\" ends with \"%s\": %t \n", refString,
endWith, ends)

}
  1. Run the code by executing go run contains.go.
  2. See the output in the Terminal: