TheDeveloperBlog.com

Home | Contact Us

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

<< Back to GO

Golang Equal String, EqualFold (If Strings Are the Same)

Test strings for equality using the equals operator in an if-statement. Use the EqualFold func.
String equals. Two strings may have the same rune content, and this is important for us to detect. The strings may have been created in different ways.Strings
In Go we can use the equality operator to test the contents of strings. This treats uppercase and lowercase characters as different—strings.EqualFold can be used for case insensitivity.
String equals example. Here we create 2 strings that end up having the same values ("catcat"). They are not the same string, but their contents are identical.

Equals: We use the double-equals sign operator to test the strings. This evaluates to true, so the "Strings are equal" message is printed.

Golang program that tests for equal strings package main import ( "fmt" "strings" ) func main() { // Create 2 equal strings in different ways. test1 := "catcat" test2 := strings.Repeat("cat", 2) // Display the strings. fmt.Println("test1:", test1) fmt.Println("test2:", test2) // Test the strings for equality. if test1 == test2 { fmt.Println("Strings are equal") } if test1 != test2 { fmt.Println("Not reached") } } Output test1: catcat test2: catcat Strings are equal
EqualFold. Uppercase letters are not equal to lowercase letters. But with EqualFold we fold cases. This makes "A" equal to "a." No string copies or conversions are required.

Tip: Using EqualFold instead of creating many strings by lowercasing them can optimize performance.

Golang program that uses EqualFold package main import ( "fmt" "strings" ) func main() { value1 := "cat" value2 := "CAT" // This returns true because cases are ignored. if strings.EqualFold(value1, value2) { fmt.Println(true) } } Output true
A review. With the equals-sign operator and strings.EqualFold, we can compare strings. Case-insensitivity is not always needed. Using the equals operator is best when it is sufficient.
© 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