What is strings.ContainsAny() in Go?
The strings package is a Go standard library package that contains functions to manipulate UTF-8 encoded strings.
The ContainsAny() method
The strings package provides the ContainsAny() method, which can be used to check if the input string contains any of the characters or Unicode code points of another string (passed as another input to the function).
A Unicode code point is an integer value that uniquely identifies a given character. There are different encodings, like UTF-8 or UTF-16, which we can use to encode the Unicode characters. Each character’s Unicode code point can be encoded as one or more bytes specified by the encodings.
Syntax
func ContainsAny(org_string, sub_string) bool
Arguments
- The method
ContainsAny()takes two arguments. The first oneorg_stringis the original string and the secondsub_stringis a substring or any string that needs to be searched within the original string.
Return values
- It returns
trueif any of the Unicode code points ofsub_stringis present inorg_string. - This method is case-sensitive.
Code
First, we imported the fmt and strings package to our program in the code below:
package mainimport ("fmt""strings")func main() {str1 := "educative.io"fmt.Println(str1, "i", strings.ContainsAny(str1, "i"))fmt.Println(str1, "xf", strings.ContainsAny(str1, "xf"))}
Explanation
-
After importing
fmt, we call theContainsAny()method witheducative.ioas the input string andias thecharslist. This returns true as the characteriis present in the string"educative.io". -
We again call the
ContainsAny()method witheducative.ioas the input string andxfas thecharslist. This returns false as both the charactersxandfare not present in the stringeducative.io. -
We show the output of all these operations using the
Println()method of thefmtpackage.
Output
The program prints the output given below and exits:
educative.io i true
educative.io xf false