AppDividend
Latest Code Tutorials

Golang String ContainsAny() Example | strings.ContainsAny() Function

0

Golang String ContainsAny() is an inbuilt function that checks whether any Unicode code points in chars are within the string. The ContainsAny() method is different from strings.Contains() because it searches for characters. If any of the values in the second string argument to ContainsAny are found, it returns true.

Golang String ContainsAny()

Golang ContainsAny() method checks whether String1 exists in String2 or not while ContainsAny will check any character of String1 that exist in String2.

Syntax

func ContainsAny(s, chars string) bool

Parameters

The first parameter is a string, and the second parameter is a character that we need to check inside the string. The second argument to ContainsAny is a set of values, and just one has to be found for the method to return true.

Return Value

The function returns a boolean value depending on the input.

Example

See the following code.

// hello.go

package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(strings.ContainsAny("appdividend", "z"))
	fmt.Println(strings.ContainsAny("appdividend", "zd"))
	fmt.Println(strings.ContainsAny("quibi", "netflix"))
	fmt.Println(strings.ContainsAny("nbcuniversal", "peacock"))
	fmt.Println(strings.ContainsAny("hulu", ""))
	fmt.Println(strings.ContainsAny("", ""))
}

Output

go run hello.go
false
true
true
true
false
false

In the first scenario, the appdividend string does not contain z, so it returns false.

In the second scenario, the appdividend string does not contain z but contains d character, so it returns true.

In the third scenario, the quibi string does not contain netflx but contain i character, so it returns true.

In the fourth scenario, the nbcuniversal string does not contain pok but contains eac characters so, it returns true.

In the fifth scenario, the hulu string does not contain an empty string, so it returns false.

In the sixth scenario, the empty string does not contain empty, so it returns false.

If it finds even one character from the string and rest of the string not, then also it returns true.

Check case sensitive or not.

Let’s see a scenario in which we put the same substring but change its case and see the output.

// hello.go

package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(strings.ContainsAny("appdividend", "DIV"))
}

Output

go run hello.go
false

That means it is case sensitive and does not return true if the same value of the string but different cases.

See also

Golang String Contains()

Golang String Join()

Golang String Fields()

How To Sort Slice In Golang

Golang String Index()

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.