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 package import( "fmt" "strings" ) //program execution starts here func main() { //given string str := "hello from educative" //given substring substr := "educative" //check if str contains substr isContains := strings.Contains(str, substr) //print the result fmt.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
.RELATED TAGS
CONTRIBUTOR
View all Courses