TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to GO

Golang strings.Contains and ContainsAny

Use the Contains and ContainsAny funcs in the strings package to find substrings in strings.
Contains. Is one string contained in another? With Contains we search one string for a certain substring. We see if the string is found.Strings
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.
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.

However: If we try to find "python," the Contains func returns false—this causes the program to print 2.

Golang program that uses strings.Contains 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) } } Output 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.

So: The second argument to ContainsAny is a set of values—just one has to be found for the method to return true.

Golang program that uses ContainsAny 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") } } Output A B C
A review. 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."Index
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf