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 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)
}

Explanation

In the above code snippet, we see the following:

  • Lines 5 to 6: We import two packages. fmt is a format package that is useful for printing. strings contains 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 substr is present in the str, using the Contains() method, and assign the returned result to variable isContains.
  • Line 22: We print the result.

Free Resources