## 🙌 Case-insensitive string comparison in Go

##### May 25, 2021
introduction strings

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.

#### ✒️ Write to a CSV file in Go

##### Learn how to write data to a CSV or TSV file
introduction file

#### 🏁 Check if a string starts with a substring in Go

##### Learn how to use strings.HasPrefix() function
introduction strings

#### ✍️ Write to a file in Go

##### Learn how to write any data to a file
introduction file