The strings
package is a Go standard library package that contains functions to manipulate UTF-8 encoded strings.
Contains()
methodThe Contains()
method can be used in Go to check if a substring is contained in a string.
func Contains(s, substr string) bool
s
and a substring substr
as input.true
if the substring is present in the input string and false
if it is not present.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, "")) }
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.
The program prints the output below and exits:
educative.io io true
educative.io shot false
educative.io true
RELATED TAGS
CONTRIBUTOR
View all Courses