๐ŸŽ“ A1Learner
๐Ÿ”

Go String Functions

The strings package is a built-in package that holds functions for working with text. Each function takes a string and returns a new value.

Checking inside a string

Contains answers if a text sits inside a string. HasPrefix answers if a string starts with a text.

package main

import "fmt"
import "strings"

func main() {
	fmt.Println(strings.Contains("programming", "gram"))
	fmt.Println(strings.HasPrefix("programming", "ing"))
}

Changing the case

ToUpper changes every letter to upper case. ToLower changes every letter to lower case.

package main

import "fmt"
import "strings"

func main() {
	fmt.Println(strings.ToUpper("GoLang"))
	fmt.Println(strings.ToLower("GoLang"))
}

Positions and counts

Index gives the position where a text first appears. Count gives how many times a text appears.

package main

import "fmt"
import "strings"

func main() {
	fmt.Println(strings.Index("programming", "gram"))
	fmt.Println(strings.Count("programming", "m"))
}

Splitting and joining

Split cuts a string at each comma. Join puts the parts back together with a comma.

package main

import "fmt"
import "strings"

func main() {
	parts := strings.Split("a,b,c", ",")
	fmt.Println(parts)
	fmt.Println(strings.Join(parts, ","))
}

Example

package main

import "fmt"
import "strings"

func main() {
	email := "hana@example.com"
	parts := strings.Split(email, "@")
	fmt.Println("User:", parts[0])
	fmt.Println("Domain:", parts[1])
}

Key points

  • Use strings.Contains to check if one text sits inside another.
  • Use strings.HasPrefix to check how a string starts.
  • Use strings.ToUpper to change every letter to upper case.
  • Use strings.ToLower to change every letter to lower case.
  • Use strings.Index to find where one text first appears.
  • Use strings.Split to cut a string into parts.
  • Use strings.Join to join parts back into one string.

In this example, email holds one address. Split cuts it at the @ sign. The first part is the user name. The second part is the domain. The prints show each part on its own line.

Note

The strings functions return new values and leave the first string unchanged.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Go Playground

Exercise

What does fmt.Println(strings.ToUpper("go")) print?