Home » Golang String ContainsAny

Golang String ContainsAny

Golang strings package ContainsAny() is a built-in function used to check if the given Unicode characters are present in the string.

It returns true if the characters in the second argument in ContainsAny() function is present in the given string else returns false.

ContainsAny() method is different from string.Contains() method as it returns true if any of the Unicode characters are present in the string however later check if the string contains a substring.

ContainsAny() Syntax

The syntax for ContainsAny() function is:

func ContainsAny(s1, chars string) bool

ContainsAny() Parameters

The ContainsAny() function take two parameters

s1
chars

ContainsAny() Return Value

The strings package ContainsAny() function returns bool value.

  • Returns true – if the s1 string contains any of the Unicode characters of the second argument.
  • Returns false – if the s1 string doesn’t contain characters of the second argument.

Let’s understand the string package ContainsAny() method with examples.

strings.ContainsAny() function to check string contains Characters in go

The following go program checks if a string contains the specified Unicode characters given in the second argument using the strings.ContainsAny() function.

package main

import (
	"fmt"
	"strings"
)

func main() {

	// Checks for characters in the string
	fmt.Println(strings.ContainsAny("Go Program", "ti"))
	fmt.Println(strings.ContainsAny("Unicode", "eu"))
	fmt.Println(strings.ContainsAny("characters", "z!"))
	fmt.Println(strings.ContainsAny("substring", "it"))

}

The output of the above string contains another string in go is:

false
true
false
true

In the above program,

the first output returns false as the string “Go Program” doesn’t contain any of the characters “ti”

The second output returns true as the character e from the “eu” in the second argument is present in the string “Unicode”.

The third output returns false as the string “characters” doesn’t contain any of the characters “z!”.

The fourth output returns true as the characters “it” in the second argument are present in the string.

Conclusion

I hope the above article on how to check if the string contains Unicode characters in golang using the ContainsAny() method is helpful to you.

You can find more topics about the Golang tutorials on the GolangSpot Home page.

Leave a Comment