Golang : Strings comparison
Given that mostly backend services deal with text data. There bound to be times when there is a need to compare strings. So how does one compare strings in Golang? After digging around....finally found out that the strings.EqualFold
function can be used to compare strings (case insensitive)
For example :
package main
import (
"fmt"
"strings"
)
func main() {
string1 := "Hello"
string2 := "World"
string3 := "HELLo"
// true
bool1 := strings.EqualFold(string1, string1)
// false
bool2 := strings.EqualFold(string1, string2)
// true
bool3 := strings.EqualFold(string1, string3)
fmt.Printf("%s is equal to %s : %v \n", string1, string1, bool1)
fmt.Printf("%s is equal to %s : %v \n", string1, string2, bool2)
// EqualFold comparison is case IN-sensitive
fmt.Printf("%s is equal to %s : %v \n", string1, string3, bool3)
}
Output :
Hello is equal to Hello : true
Hello is equal to World : false
Hello is equal to HELLo : true
Reference :
See also : Golang : Regular Expression find string example
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+40.9k Golang : Get hardware information such as disk, memory and CPU usage
+37.8k Golang : Remove dashes(or any character) from string
+8.2k Golang : Temperatures conversion example
+5.2k Golang : How to solve "too many .rsrc sections" error?
+32.1k Golang : Converting a negative number to positive number
+16.8k Golang : Display list of time zones with GMT
+6.2k Golang : Example of custom handler for Gorilla's Path usage.
+10.8k Golang : Convert a rune to unicode style string \u
+11.4k Golang : Exit, terminating or aborting a program
+12.1k Swift : Convert (cast) Int to String ?
+17.2k Golang : Generate thumbnails from images
+12.3k Golang : Verify token from Google Authenticator App