How to check if a string contains a substring in Golang
Overview
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.
Syntax
strings.Contains(str, substr)
Parameters
This method accepts two parameters:
- We pass
stras the first parameter. - We pass
substras the second parameter.
Returns
This method returns a boolean value.
If str contains substr, it returns true. Otherwise, it returns false.
Example
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)}
Explanation
- Lines 5–6: We import the following packages.
fmt: This is a format package useful for printing.strings: TheContains()method is provided by thestringspackage, which is useful to check whether or not a string contains a substring.
- Line 13: We declare and initialize the string,
str. - Line 16: We declare and initialize the substring,
substr. - Line 19: We check if a
substris present in thestrusing theContains()method and assign the returned result to theisContainsvariable.