In this shot, we learn to check whether or not a string contains a substring using Golang.
We can use the Contains()
method provided by the strings
package to find the string’s substring.
strings.Contains(str, substr)
This method accepts two parameters:
str
as the first parameter.substr
as the second parameter.This method returns a boolean value.
If str
contains substr
, it returns true
. Otherwise, it returns false
.
In this example, we will check whether or not the string str
"Hello from educative"
contains the substring substr
"educative"
.
package main//import format and strings packageimport("fmt""strings")//program execution starts herefunc main() {//given stringstr := "hello from educative"//given substringsubstr := "educative"//check if str contains substrisContains := strings.Contains(str, substr)//print the resultfmt.Println(isContains)}
fmt
: This is a format package useful for printing.strings
: The Contains()
method is provided by the strings
package, which is useful to check whether or not a string contains a substring.str
.substr
.substr
is present in the str
using the Contains()
method and assign the returned result to the isContains
variable.