How check if a string contains a substring in Golang

Last updated on Jun 22, 2021 by Suraj Sharma



In this tutorial, you will learn to use the Contains function implemented the Golang package strings

The Contains function checks whether a substring is present in a given string or not.

strings.Contains function accepts two arguments; first is the original string and the second is a substring to check for


Check if a string contains a substring


package main

import (
    "fmt"
    "strings"
)

func main () {
    str := "Golang programming Language"
    substr := "gram"

    if ok := strings.Contains(str, substr); ok {
        fmt.Printf("string [%s] contains substring [%s]", str, substr)
    } else {
        fmt.Printf("string [%s] does not contain substring [%s]", str, substr)
    }
}


Related Solutions


Rate this post


Suraj Sharma is the founder of Future Gen AI Services. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.