To compare two strings in Go, you can use the comparison operators ==
, !=
, >=
, <=
, <
, >
. Alternatively, you can use the strings.Compare()
function from the strings
package.
When comparing strings, we mean lexicographic (alphabetical) order.
Comparison operators
Strings in Go support comparison operators ==
, !=
, >=
, <=
, <
, >
to compare strings in lexicographic (alphabetical) order. The result of the comparison is a bool
value (true
or false
) indicating if the condition is met.
Example:
package main
import "fmt"
func main() {
str1 := "gosamples"
str2 := "dev"
str3 := "gosamples"
fmt.Printf("%s == %s: %t\n", str1, str2, str1 == str2)
fmt.Printf("%s == %s: %t\n", str1, str3, str1 == str3)
fmt.Printf("%s != %s: %t\n", str1, str2, str1 != str2)
fmt.Printf("%s != %s: %t\n\n", str1, str3, str1 != str3)
fmt.Printf("%s >= %s: %t\n", str1, str2, str1 >= str2)
fmt.Printf("%s >= %s: %t\n", str1, str3, str1 >= str3)
fmt.Printf("%s > %s: %t\n", str1, str2, str1 > str2)
fmt.Printf("%s > %s: %t\n\n", str1, str3, str1 > str3)
fmt.Printf("%s <= %s: %t\n", str1, str2, str1 <= str2)
fmt.Printf("%s <= %s: %t\n", str1, str3, str1 <= str3)
fmt.Printf("%s < %s: %t\n", str1, str2, str1 < str2)
fmt.Printf("%s < %s: %t\n", str1, str3, str1 < str3)
}
Output:
gosamples == dev: false
gosamples == gosamples: true
gosamples != dev: true
gosamples != gosamples: false
gosamples >= dev: true
gosamples >= gosamples: true
gosamples > dev: true
gosamples > gosamples: false
gosamples <= dev: false
gosamples <= gosamples: true
gosamples < dev: false
gosamples < gosamples: false
The strings.Compare()
function
The strings.Compare()
function compares two strings in lexicographic order returning an int
value as a result:
The result is:
0
ifa == b
1
ifa > b
-1
ifa < b
Example:
package main
import (
"fmt"
"strings"
)
func main() {
str1 := "gosamples"
str2 := "dev"
str3 := "gosamples"
fmt.Printf("strings.Compare(%s, %s): %d\n", str1, str2, strings.Compare(str1, str2))
fmt.Printf("strings.Compare(%s, %s): %d\n", str1, str3, strings.Compare(str1, str3))
fmt.Printf("strings.Compare(%s, %s): %d\n", str2, str1, strings.Compare(str2, str1))
}
Output:
strings.Compare(gosamples, dev): 1
strings.Compare(gosamples, gosamples): 0
strings.Compare(dev, gosamples): -1
Case-insensitive string comparison
If you want to compare whether two strings are equal without paying attention to the case, you can perform a case-insensitive string comparison. Check out how to do it in our other tutorial.