What is the string.Contains function in Golang?

The Contains function tells us whether a substring appears inside a string or not.

To use this function, you must import the strings package in your file and access the Contains function within it using the . notation like so: string.Contains.

Here, Contains is the actual function, while string is the Go package that stores the definition of this function.

Syntax

func Contains(str, substr string) bool

Parameters

The Contains function takes two arguments:

  • str: This argument is of the string type and represents the text you want to search in.

  • substr: This argument is also of string type and represents the part of the text that you want to search inside the other string.

Return value

The Contains function returns true if it is able to find the string substr inside str, otherwise false is returned.

Code

Below is a simple example where we use the Contains function to check if “ee” is present inside a string.

package main
import (
"fmt"
"strings"
)
func main() {
str := "Beep Beep"
substr := "ee"
check:= strings.Contains(str,substr)
if check{
fmt.Print("We found \"",substr,"\" in \"",str,"\"")
} else{
fmt.Print("\"", substr,"\" is not in \"",str,"\"")
}
}

Now, this is an example where the Contains function fails to find the substring.

package main
import (
"fmt"
"strings"
)
func main() {
str := "Hola Amigos!!"
substr := "ee"
check:= strings.Contains(str,substr)
if check{
fmt.Print("We found \"",substr,"\" in \"",str,"\"")
} else{
fmt.Print("\"", substr,"\" is not in \"",str,"\"")
}
}
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources

Attributions:
  1. undefined by undefined