In this shot, we’ll learn how to check if a substring is included in the string, using Golang.
We can use the Contains()
method, provided by the strings
package.
strings.Contains(str, substr)
This method will accept two parameters:
str
) as the first parameter.substr
) as the second parameter.This method will return a Boolean value.
If str
contains substr
, the method returns true
. Otherwise, it will return false
.
The given string is Hello from educative
, and the substring is educative
.
In this example, we will check if the substring educative
is present in the string Hello from 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)}
In the above code snippet, we see the following:
fmt
is a format package that is useful for printing. strings
contains a method that has been provided by the strings package.main()
function in Golang.str
.substr
.substr
is present in the str
, using the Contains()
method, and assign the returned result to variable isContains
.