Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

go
golang
contains
communitycreator
strings

How to check if a substring is contained in a string in Go

Siddharth Singh

The strings package is a Go standard library package that contains functions to manipulate UTF-8 encoded strings.

The Contains() method

The Contains() method can be used in Go to check if a substring is contained in a string.

Syntax

func Contains(s, substr string) bool

Arguments

  • This method takes the string s and a substring substr as input.

Returns

  • It returns true if the substring is present in the input string and false if it is not present.
  • This method is case-sensitive.

Code

First, we import the fmt and strings package to our program in the code below:

package main

import (
	"fmt"
	"strings"
)

func main() {
  str1 := "educative.io"
	fmt.Println(str1, "io", strings.Contains(str1, "io"))
	fmt.Println(str1, "shot", strings.Contains(str1, "shot"))
	fmt.Println(str1, "", strings.Contains(str1, ""))
}

Explanation

  • We call the Contains() method with "educative.io" as the input string and "io" as the substring to search after importing fmt. This returns true becuase the input substring "io" is contained in the string "educative.io".

  • We call the Contains() method with "educative.io" as the input string and "shot" as the substring to search. This returns false because the input substring "shot" is not contained in the string "educative.io".

  • We test the Contains() method with "educative.io" as the input string and empty string("") as the substring to search. This returns true because all strings contain the empty string.

  • We show the output of all these operations using the Println() method of the fmt package.

Output

The program prints the output below and exits:

educative.io io true
educative.io shot false
educative.io  true

RELATED TAGS

go
golang
contains
communitycreator
strings
RELATED COURSES

View all Courses

Keep Exploring