In this blog, we will learn how to compare strings in Golang.
First we will learn simple string comparison in Golang using relational operator i.e, ==, !=, >=, <=, <, >.
Compare String using Relational Operators
fmt.Println("abc == abc :", "abc" == "abc")
fmt.Println("abc == ABC :", "abc" == "ABC")
fmt.Println("abc == def :", "abc" < "def")
fmt.Println("abc == def :", "abc" > "def")
abc == abc : true
abc == ABC : false
abc == def : false
def == abc : false
String Comparision in Golang using the relational operators is case-sensitive.
Let’s see another way of comparing strings i.e compare function in the strings package.
Golang String Comparison using Compare Function
The Golang String Package has a Compare function which returns an integer comparing two strings lexicographically.
func Compare(s, t string) int
Compare Function | Return Value |
---|---|
string1 == string2 | 0 |
string1 < string2 | -1 |
string1 > string2 | +1 |
fmt.Println(strings.Compare("abc", "abc"))
fmt.Println(strings.Compare("bca", "cba"))
fmt.Println(strings.Compare("bca", "abc"))
Output:
0
-1
1
The Compare function is also case-sensitive.
Example:
fmt.Println(strings.Compare("a", "a"))
fmt.Println(strings.Compare("A", "a"))
fmt.Println(strings.Compare("a", "A"))
Output:
0
-1
1
Golang Strings Package Compare function compares according to the ASCII value.
A-Z has ASCII value of 65-90 while a-z has ASCII value of 97-122, and by this a > A and thus the compare function returns +1.
The above two string comparison ways discussed above were case-sensitive, let’s now see a case-insensitive way to compare strings.
Golang String EqualFold
func EqualFold(s, t string) bool
EqualFold is a case-insensitive way of comparing two strings in Golang. The Function returns bool value, it checks for equality in both the strings.
Example:
fmt.Println(strings.EqualFold("Golang", "Golang"))
fmt.Println(strings.EqualFold("Golang", "Go"))
fmt.Println(strings.EqualFold("Golang", "goLANG"))
fmt.Println(strings.EqualFold("Golang", "go"))
Output:
true
false
true
false
Read datatypes in Golang to have better understanding of string comparison in Golang.
Learn more about Golang Strings Package from the official Documentation.