Go - String Functions

In this tutorial, we will learn important functions of the standard library’s strings package in Go with examples.

The standard library’s strings package provides many useful string-related functions.

Go - String Functions with Examples

Here’s a sample of the functions available in strings. Since these are functions from the package, not methods on the string object itself, we need to pass the string in question as to the first argument to the function.

package main

import (
    s "strings"

func main() {

    fmt.Println("Contains:  ", s.Contains("sourcecodeexamples", "examples"))
    fmt.Println("Count:     ", s.Count("sourcecodeexamples", "code"))
    fmt.Println("HasPrefix: ", s.HasPrefix("sourcecodeexamples", "source"))
    fmt.Println("HasSuffix: ", s.HasSuffix("sourcecodeexamples", "examples"))
    fmt.Println("Index:     ", s.Index("sourcecodeexamples", "c"))
    fmt.Println("Join:      ", s.Join([]string{"source", "code", "examples"}, "-"))
    fmt.Println("Repeat:    ", s.Repeat("code", 5))
    fmt.Println("Replace:   ", s.Replace("foo", "o", "0", -1))
    fmt.Println("Replace:   ", s.Replace("foo", "o", "0", 1))
    fmt.Println("Split:     ", s.Split("source-code-examples", "-"))
    fmt.Println("ToLower:   ", s.ToLower("SOURCECODEEXAMPLES"))
    fmt.Println("ToUpper:   ", s.ToUpper("sourcecodeexamples"))

    fmt.Println("Len: ", len("sourcecodeexamples"))
    fmt.Println("Char:", "sourcecodeexamples"[6])


Contains:   true
Count:      1
HasPrefix:  true
HasSuffix:  true
Index:      4
Join:       source-code-examples
Repeat:     codecodecodecodecode
Replace:    f00
Replace:    f0o
Split:      [source code examples]
ToLower:    sourcecodeexamples

Len:  18
Char: 99