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
+9.3k nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
+20.4k Golang : Determine if directory is empty with os.File.Readdir() function
+22.3k Golang : Match strings by wildcard patterns with filepath.Match() function
+10.7k Golang : How to unmarshal JSON inner/nested value and assign to specific struct?
+39.1k Golang : How to iterate over a []string(array)
+19.7k Golang : Get current URL example
+29.9k Golang : Record voice(audio) from microphone to .WAV file
+5.3k Golang : Calculate half life decay example
+11k Golang : Replace a parameter's value inside a configuration file example
+21.6k Golang : How to read float value from standard input ?
+10.7k Golang : Interfacing with PayPal's IPN(Instant Payment Notification) example
+22.1k Fix "Failed to start php5-fpm.service: Unit php5-fpm.service is masked."