Comparing Strings in GoLang

Comparing strings together is an important task that is almost unavoidable in large programs. In this post, we will see different ways of comparing strings in GoLang.

1. Using the GoLang Comparison Operators

There is a multitude of comparison operators in Go. Each operator works in the way it looks. We will see what are the ways of using them to compare strings in Go.

1.1) The double equals operator

The double equal is an operator which essentially compares two strings on each side of it and returns the boolean value of the comparison result. That is if they match the result is true and if they don’t, it’s false.

package main

import (
	"fmt"
)

func main() {
	a := "Hello"
	b := "Hi"
	chk := a == b  // checks if they are equal

	fmt.Println(chk)  // false
}

1.2) The inequality operator

The inequality operator works just like the equality operator except the output is reversed. Here is the inequality operator used in string comparison.

package main

import (
	"fmt"
)

func main() {
	a := "abc"
	b := "Abc"
	chk := a != b  // checks if they are equal

	fmt.Println(chk)  // true
}

1.3) The general comparison operators

The comparison operators work in the lexicographical comparison. If it fulfills the condition then it’s true and for all other cases, it’s false. Below is the example of comparison operators in action.

package main

import (
	"fmt"
)

func main() {
	s1 := "abc"
	s2 := "cab"
		
	v := s1 > s2
	v1 := s1 < s2
	v2 := s1 >= s2
	v3 := s1 <= s2

	fmt.Println(v)  // false
	fmt.Println(v1)  // true
	fmt.Println(v2)  // false
	fmt.Println(v3)  // true
}

2. GoLang Strings Compare() method

The strings package contains a compare method. The signature of this method is shown below. 

func Compare(s1, s2 string) int
package main

import (
	"fmt"
	"strings"
)

func main() {
	s1 := "abc"
	s2 := "cab"
	
	v := strings.Compare(s1, s2)
	
	fmt.Println(v) // -1
}

As you can see, it returns o if they are the same. If the first one is greater then it returns 1. If it’s lesser then it returns -1. The greater and lesser values are defined by their lexicographical order. 

3. Strings EqualFold() method to compare strings

The EqualFold method in the strings package can be used for string equality. It does this irrespective of string cases. So, we can check two strings without any extra conversion of cases. It is a very efficient method of checking string equality.

package main

import (
	"fmt"
	"strings"
)

func main() {
	s1 := "XyZ"
	s2 := "xYz"
	
	v := strings.EqualFold(s1, s2)  // cases don't matter
	
	fmt.Println(v) // true
}