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 str as the first parameter.
  • We pass substr as 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 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

  • Lines 5–6: We import the following packages.
    • fmt: This is a format package useful for printing.
    • strings: The Contains() method is provided by the strings package, 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 substr is present in the str using the Contains() method and assign the returned result to the isContains variable.
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources