Cookies management by TermsFeed Cookie Consent

๐Ÿ™Œ Case-insensitive string comparison in Go

introduction strings

Please disable your ad blocker ๐Ÿ™‚. Our ads are not intrusive

Is there a case-insensitive string comparison function in Go? Of course! Although the name does not seem to indicate it, strings.EqualFold deals with it:

package main

import (
    "fmt"
    "strings"
)

func main() {
    foo1 := "foo"
    foo2 := "FOO"
    fmt.Println(strings.EqualFold(foo1, foo2))
}

You may ask now why we canโ€™t convert both strings to upper or lowercase and, in this way, compare if they are case-insensitive equal. Of course, it works, but not for any case and any language. For example, in Greek, there are 3 forms of sigma letter:

g1 := "ฯ‚" // a final lowercase sigma
g2 := "ฮฃ" // a capital sigma
g3 := "ฯƒ" // a non-final sigma

fmt.Println(strings.ToLower(g1))
fmt.Println(strings.ToLower(g2))
fmt.Println(strings.ToLower(g3))

fmt.Println(strings.EqualFold(g1, g2))
fmt.Println(strings.EqualFold(g1, g3))
fmt.Println(strings.EqualFold(g2, g3))

Output:

ฯ‚
ฯƒ
ฯƒ
true
true
true

Converting them to lowercase doesnโ€™t give the same form, but a comparison using strings.EqualFold informs that they are equal. This is because strings.EqualFold uses case folding (now itโ€™s clear why the function is named EqualFold) method which respects the case rules of different languages, so it always should be preffered method of case-insensitive comparison.


Thank you for being on our site ๐Ÿ˜Š. If you like our tutorials and examples, please consider supporting us with a cup of coffee and we'll turn it into more great Go examples.

Have a great day!

Buy Me A Coffee

๐Ÿ’ Concatenate strings in Go

Learn the differences between string concatenation methods
introduction strings

๐Ÿ–จ๏ธ Convert string to []byte or []byte to string in Go

Learn the difference between a string and a byte slice
introduction strings slice

๐Ÿ”Ÿ Convert string to bool in Go

Learn how to parse a string as a bool
introduction strings bool