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
+12.9k Golang : Google Drive API upload and rename example
+16.9k Golang : Get download file size
+6.1k Golang : Array mapping with Interface
+31.2k Golang : How to check if a date is within certain range?
+22.1k Golang : minus time with Time.Add() or Time.AddDate() functions to calculate past date
+5.7k Golang : Check if password length meet the requirement
+16k Golang : How to make a file read only and set it to writable again?
+7.7k Golang : Gorilla web tool kit schema example
+11.2k Golang : How to check if a string starts or ends with certain characters or words?
+10.6k Golang : Calculations using complex numbers example
+7.9k Golang : How to get username from email address
+11.5k Golang : How to calculate the distance between two coordinates using Haversine formula