How to find a substring using Golang
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.
Syntax
strings.Contains(str, substr)
Parameters
This method will accept two parameters:
- First: Pass the string (
str) as the first parameter. - Second: Pass the substring (
substr) as the second parameter.
Return values
This method will return a Boolean value.
If str contains substr, the method returns true. Otherwise, it will return false.
Example
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.
Code
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
In the above code snippet, we see the following:
- Lines 5 to 6: We import two packages.
fmtis a format package that is useful for printing.stringscontains a method that has been provided by the strings package. - Line 10: The program execution starts from the
main()function in Golang. - Line 13: We declare and initialize the string
str. - Line 16: We declare and initialize the substring
substr. - Line 19: We check if the
substris present in thestr, using theContains()method, and assign the returned result to variableisContains. - Line 22: We print the result.