How check if a string contains a substring in Go

#go

Last updated on Jun 22, 2021 by Suraj Sharma



In this tutorial, you will learn to use the Contains function implemented the Go 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 := "Go 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 a Full Stack Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.