Welcome To Golang By Example

Check if a string contains another string in Go (Golang)

Table of Contents

Overview

In Golang string are UTF-8 encoded. strings package of GO provides a Contains method that can be used to check if a particular string is a substring of another string.

Below is the signature of the function

func Contains(s, substr string) bool

As you can notice the return value of the Compare function is an bool . This value will be

Code:

package main

import (
    "fmt"
    "strings"
)

func main() {
    present := strings.Contains("abc", "ab")
    fmt.Println(present)

    present = strings.Contains("abc", "xyz")
    fmt.Println(present)
}

Output:

true
false