Case insensitive string comparison in Go

36,281

Solution 1

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"))
}

Solution 2

method 1:

func CompareStringsInCrudeWay(stringA, stringB string) (bool, error) {
  if strings.ToLower(stringA) == strings.ToLower(stringB) {
      return true, nil
  } else {
      return false, nil
  }
}

method 2:

func Compare(stringA, stringB string) bool {
  for i := 0; i < len(stringA); i++ {
      if stringA[i] == stringB[i] {
          continue
      }
      if unicode.ToLower(stringA[i]) != unicode.ToLower(stringB[i]) {
          return false
      }
  }
  return true
}

method 3:

func CompareStringsInEfficientWay(stringA, stringB string) (bool, error) {
   if strings.EqualFold(stringA, stringB) {
      return true, nil
   } else {
      return false, nil
   }
}

method 3 is actually wrapping method 2, and both are efficient. You can check this blog for more explanation.

Share:
36,281

Related videos on Youtube

user7610
Author by

user7610

Software Quality Engineer at Red Hat

Updated on July 09, 2022

Comments

  • user7610
    user7610 almost 2 years

    How do I compare strings in a case insensitive manner?

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

  • lunicon
    lunicon over 4 years
    EqualFold not compare :(
  • lunicon
    lunicon over 4 years
    Sorting can use strings.ToLower("Go") < strings.ToLower("go")
  • KBN
    KBN over 3 years
    > EqualFold not compare @lunicon what do you mean?
  • lunicon
    lunicon over 3 years
    @KBN, compare operation can say "more, less or equals", EqualFold retrun boolean
  • Vitaly Zdanevich
    Vitaly Zdanevich over 2 years
    Please paste code as code, not as images.