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_string is the original string and the second sub_string is a substring or any string that needs to be searched within the original string.

Return values

  • It returns true if any of the Unicode code points of sub_string is present in org_string.
  • This method is case-sensitive.
Using ContainsAny() to find if any of the input chars are present in a string

Code

First, we imported 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, "i", strings.ContainsAny(str1, "i"))
fmt.Println(str1, "xf", strings.ContainsAny(str1, "xf"))
}

Explanation

  • After importing fmt, we call the ContainsAny() method with educative.io as the input string and i as the chars list. This returns true as the character i is present in the string "educative.io".

  • We again call the ContainsAny() method with educative.io as the input string and xf as the chars list. This returns false as both the characters x and f are not present in the string educative.io.

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

Output

The program prints the output given below and exits:

educative.io i true
educative.io xf false

Free Resources