Home
Go
strings.Contains and ContainsAny
Updated Dec 28, 2024
Dot Net Perls
Contains. Is one string contained in another? With Contains we search one string for a certain substring. We see if the string is found.
With other funcs like ContainsAny we search for characters. If any of a set of characters is found in the string, ContainsAny will return true.
strings.Index
slices.Contains
First example. We have a string that contains "this is a test." The word "test" is found in the string. When we invoke Contains and search for "test," we receive true.
Argument 1 The first argument to Contains is a string. It is the string we are searching inside.
Argument 2 The second argument is the value we are searching for within the first argument.
package main import ( "fmt" "strings" ) func main() { value1 := "test" value2 := "python" source := "this is a test" // This succeeds. // ... The substring is contained in the source string. if strings.Contains(source, value1) { fmt.Println(1) } // Contains returns false here. if !strings.Contains(source, value2) { fmt.Println(2) } }
1 2
ContainsAny. This method is different from Contains—it searches for characters. If any of the values in the second string argument to ContainsAny are found, it returns true.
Argument 1 The first argument to ContainsAny is the string we are searching for values within.
Argument 2 This is a set of values—just one has to be found for the method to return true.
package main import ( "fmt" "strings" ) func main() { source := "12345" // See if 1, 3 or 5 are in the string. if strings.ContainsAny(source, "135") { fmt.Println("A") } // See if any of these 3 chars are in the string. if strings.ContainsAny(source, "543") { fmt.Println("B") } // The string does not contain a question mark. if !strings.ContainsAny(source, "?") { fmt.Println("C") } }
A B C
Contains is clearer than Index() when we just need to test existence. We can test against true and false, not the magical value -1 that Index() returns to mean "not found."
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Dec 28, 2024 (edit link).
Home
Changes
© 2007-2025 Sam Allen