How to use ContainsAny() function in Golang?

Go ProgrammingServer Side ProgrammingProgramming

Golang has a built-in string function called ContainsAny() that we can use to check whether a specified string is present in a given string or not.

ContainsAny() is completely different from Contains().

  • Contains() is used to detect if a string contains a substring.

  • ContainsAny() is used to detect if a string contains any characters in the provided string. Even if one character of the specified string is present in the original given string, then it returns True, else False.

Syntax

func ContainsAny(s, chars string) bool

Where,

  • s – Original String

  • chars string – Substring where we define the string or characters.

It returns a Boolean value.

Example

ContainsAny() is case-sensitive, which is demonstrated in the following example.

package main
import (
   "fmt"
   "strings"
)
func main() {
   // Initializing the Strings
   x := "golang programming"
   y := "GO"
   
   // using the ContainsAny
   opt := strings.ContainsAny(x, y)
   
   // Display the ContainsAny Output
   fmt.Println("ContainsAny :", opt)
}

Output

It will produce the following output −

ContainsAny : false

Observe that the string contains the characters from the sub-string but due to the case mismatch, ContainsAny returns False.

Example

Let us take another example −

package main
// importing fmt and strings
import (
   "fmt"
   "strings"
)
func main() {
   // Initializing the Strings
   p := "Function"
   q := "Programming"
   r := "language"
   s := "method"
   
   // using the ContainsAny
   test1 := strings.ContainsAny(p, q)
   test2 := strings.ContainsAny(r, s)
   test3 := strings.ContainsAny(s, p)
   test4 := strings.ContainsAny(q, s)
   
   // Display the ContainsAny Output
   fmt.Println("ContainsAny of test1 :", test1)
   fmt.Println("ContainsAny of test2 :", test2)
   fmt.Println("ContainsAny of test3 :", test3)
   fmt.Println("ContainsAny of test4 :", test4)
}

Output

On execution, it will produce the following output −

ContainsAny of test1 : true
ContainsAny of test2 : true
ContainsAny of test3 : true
ContainsAny of test4 : true
raja
Updated on 14-Mar-2022 05:41:25

Advertisements