Menu Close

Go – bytes.ContainsAny() function in go

bytes.ContainsAny() function is used to check whether any of the UTF-8-encoded string code points are within another slice in go.

It means, we can check UTF-8 encoded string within another byte slice.

bytes.ContainsAny() function prototype:

func ContainsAny(b []byte, chars string) bool

Input parameters:
b: byte slice
chars: String (Could be UTF-8-encoded)

bytes.ContainsAny() function return value:

bytes.ContainsAny() function returns true If UTF-8-encoded string is present within another byte slice else false.

Explanation:

1)
b := []byte("I like vegetable.")
str := "tÄo!"
Output: true

Here, "t" in str is present in b i.e "I like vegetable."

2)
b := []byte("I like vegetable.")
str := "去是伟大的."
Output: true

Here, "." in str is present in b i.e "I like vegetable."

3) b := []byte("I like vegetable.")
str := "Yo"
Output: false

Here, None of the characters of str is present in b i.e "I like vegetable."

Example:

package main

import (
	"bytes"
	"fmt"
)

func main() {
    b := []byte("I like vegetable.")
    str := "tÄo!"
	fmt.Println(bytes.ContainsAny(b, str))
	
	b = []byte("I like vegetable.")
	str = "去是伟大的."
	fmt.Println(bytes.ContainsAny(b, str))
	
	b = []byte("I like vegetable.")
	str = "Yo"
	fmt.Println(bytes.ContainsAny(b, str))
	
	b = []byte("")
	str = ""
	fmt.Println(bytes.ContainsAny(b, str))
	
	b = []byte{10, 20, 30, 40}
	str = "2"
	fmt.Println(bytes.ContainsAny(b, str))
}

Output:

true
true
false
false
false

To learn more about golang, Please refer given below link:

References:

https://golang.org/doc/

Posted in bytes, golang, packages

Leave a Reply

Your email address will not be published. Required fields are marked *