Check if the specified element is present in the slice of bytes in Golang
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. In the Go slice of bytes, you can check the given slice contain the specified element or not using the following functions. These functions are defined under the bytes package so, you have to import bytes package in your program for accessing these functions.
1. Contains: This function is used to check whether the specified element is present or not in the given slice of bytes. This method returns true if the element present in the slice, or return false if the element is not present in the given slice.
Syntax:
func Contains(slice_1, sub_slice []byte) bool
Example:
package main
import (
"bytes"
"fmt"
)
func main() {
slice_1 := []byte{ 'A' , 'N' , 'M' ,
'O' , 'P' , 'Q' }
res1 := bytes.Contains(slice_1, []byte{ 'A' })
res2 := bytes.Contains(slice_1, []byte{ 'x' })
res3 := bytes.Contains([]byte( "GeeksforGeeks" ), []byte( "ks" ))
res4 := bytes.Contains([]byte( "Geeks" ), []byte( "" ))
res5 := bytes.Contains([]byte( "" ), []byte( "" ))
fmt.Println( "Result 1:" , res1)
fmt.Println( "Result 2:" , res2)
fmt.Println( "Result 3:" , res3)
fmt.Println( "Result 4:" , res4)
fmt.Println( "Result 5:" , res5)
}
|
Output:
Result 1: true
Result 2: false
Result 3: true
Result 4: true
Result 5: true
2. ContainsAny: This function is used to check whether any of the UTF-8-encoded code points in chars is present or not in the given slice of bytes. This method returns true if any of the UTF-8-encoded code points in chars is present in the slice, or return false if any of the UTF-8-encoded code points in chars is not present in the given slice.
Syntax:
func ContainsAny(slice_1 []byte, charstr string) bool
Example:
package main
import (
"bytes"
"fmt"
)
func main() {
slice_1 := []byte{ 'A' , 'N' , 'M' , 'O' , 'P' , 'Q' }
res1 := bytes.ContainsAny(slice_1, "A" )
res2 := bytes.ContainsAny(slice_1, "a" )
res3 := bytes.ContainsAny([]byte( "GeeksforGeeks" ), "ksjkd" )
res4 := bytes.ContainsAny([]byte( "Geeks" ), "" )
res5 := bytes.ContainsAny([]byte( "" ), "" )
fmt.Println( "Result 1:" , res1)
fmt.Println( "Result 2:" , res2)
fmt.Println( "Result 3:" , res3)
fmt.Println( "Result 4:" , res4)
fmt.Println( "Result 5:" , res5)
}
|
Output:
Result 1: true
Result 2: false
Result 3: true
Result 4: false
Result 5: false
Last Updated :
26 Aug, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...