How to compare two Strings in GoLang | GoLang Tutorial

5 years ago Lalit Bhagtani 0

In this tutorial, we will learn about how to compare two strings in Go programming language.

Comparison Operators

The comparison operators like ==, != can be use to compare two strings. Operators works in the following way :-

  1. == :- It returns true, if both strings are equal otherwise it returns false.
  2. !=  :- It returns false, if both strings are equal otherwise it returns true.

Syntax

(a string) Operator (b string)

Example

package main

import (
    "fmt"
)

func main() {

    var (
	a string = "Robert"
	b string = "Robert"
	c string = "john"
    )
    fmt.Println(a == b)
    fmt.Println(a != b)
    fmt.Println(a == c)
    fmt.Println(a != c)
}

Output

true
false
false
true

String Compare

Two strings can be compare using Compare() function provided in the strings package. This function compares two string (a and b) lexicographically. It returns 0, if both strings are equal (a == b), -1 if first string is lesser than second string (a < b) and 1 if first string is greater than second string (a > b).

Syntax

func Compare(a, b string) int

Example

package main

import (
    "fmt"
    "strings"
)

func main() {

    var (
	a string = "Robert"
	b string = "Robert"
	c string = "john"
    )

    fmt.Println(strings.Compare(a, b))
    fmt.Println(strings.Compare(a, c))
    fmt.Println(strings.Compare(c, a))
}

Output

0
-1
1

String EqualFold

The function EqualFold() provided in the strings package checks the equality of two strings. It compares two strings by ignoring their cases. It returns true, if both strings are equal (a == b) and returns false, if both strings are not equal.

Syntax

func EqualFold(a, b string) bool

Example

package main

import (
    "fmt"
    "strings"
)

func main() {

    fmt.Println(strings.EqualFold("ROBERT", "ROBERT"))
    fmt.Println(strings.EqualFold("ROBERT", "robert"))
    fmt.Println(strings.EqualFold("ROBERT", "john"))
    fmt.Println(strings.EqualFold("ROBERT", "rObErT"))

}

Output

true
true
false
true

References

  1. Compare function Docs

That’s all for how to compare two strings in Go programming language. if you liked it, please share your thoughts in comments section and share it with others too.