Case insensitive string comparison in Go
Asked Answered
C

2

64

How do I compare strings in a case insensitive manner?

For example, "Go" and "go" should be considered equal.

Corticosteroid answered 12/5, 2015 at 16:38 Comment(0)
C
119

https://golang.org/pkg/strings/#EqualFold is the function you are looking for. It is used like this (example from the linked documentation):

package main

import (
    "fmt"
    "strings"
)

func main() {
    fmt.Println(strings.EqualFold("Go", "go"))
}
Corticosteroid answered 12/5, 2015 at 16:41 Comment(4)
EqualFold not compare :(Oldie
Sorting can use strings.ToLower("Go") < strings.ToLower("go")Oldie
> EqualFold not compare @Oldie what do you mean?Eugene
@KBN, compare operation can say "more, less or equals", EqualFold retrun booleanOldie
E
1

There is alternative to strings.EqualFold, there is bytes.EqualFold which work in same way

package main

import (
    "bytes"
    "fmt"
)

func main() {
    fmt.Println(bytes.EqualFold([]byte("Go"), []byte("go")))
}

https://golang.org/pkg/bytes/#EqualFold

Endpaper answered 3/6, 2021 at 8:48 Comment(2)
Please paste code as code, not as images.Limerick
Note that this makes a copy of each string, which is then immediately discarded. So if you don't already have byte slices, use strings.EqualFold.Compass

© 2022 - 2024 — McMap. All rights reserved.