How to check if a substring is contained in a string in Go
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
sand a substringsubstras input.
Returns
- It returns
trueif the substring is present in the input string andfalseif 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 mainimport ("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 importingfmt. This returnstruebecuase 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 returnsfalsebecause 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 returnstruebecause all strings contain the empty string. -
We show the output of all these operations using the
Println()method of thefmtpackage.
Output
The program prints the output below and exits:
educative.io io true
educative.io shot false
educative.io true