Go String Package

Question Click to View Answer

What does the following code print?

package main

import (
    "fmt"
    "strings"
)

func main() {
    fmt.Println(strings.Contains("nightman", "night"))
}

true is printed.

The strings package is imported to access the Contains() function.

The Contains() function returns true if the second argument is a substring of the first argument. In this example, "night" is a substring of "nightman", so true is returned.

The Go Standard Library is famous for being well written and expansive. strings is one of many packages included in the Go Standard Library.

Write some code that'll convert the "SPEAK QUIETLY" string to all lowercase letters.

strings.ToLower("SPEAK QUIETLY")

Write code that uppercases all the letters in "hI THere".

strings.ToUpper("hI THere")

Write code that converts "this", "cool", and "webpage" to "this-cool-webpage".

strings.Join([]string{"this", "cool", "webpage"}, "-")

Write code that converts "ruby/intermediate/hash-class" to []string{"ruby", "intermediate", "hash-class"}.

strings.Split("ruby/intermediate/hash-class", "/")

Write code that returns true because the string "bumfuzzle" starts with the string "bum".

strings.HasPrefix("bumfuzzle", "bum")

Write code that returns the position of the letter "p" in the word "amplify" (hint: your code should return 2).

strings.Index("amplify", "p")

Write code that converts the string "zapper" to the string "dapper" by replacing the first character.

strings.Replace("zapper", "z", "d", 1)

Write code that converts the string "funny" to the string "fuzzy" by replacing "n" with "z".

strings.Replace("funny", "n", "z", -1)

strings.Replace("funny", "n", "z", 2) would also work. The last argument indicates how many letters should be replaced. In this case, we need two letters replaced. -1 means that all the matching letters should be replaced.

Calculate the number of "g" in the string "mungingdata".

strings.Count("mungingdata", "g")

Write code that returns true because the string "gardyloo" ends with the string "loo".

strings.HasSuffix("gardyloo", "loo")