Go – Compare Strings

To compare strings in Go programming, we can use Compare function in strings package.

In addition to Compare function we can also use Comparison Operators.

In this tutorial, we will go through Compare function and Comparison Operators to compare strings.

Compare strings using Compare function

The definition of Compare function is

func Compare(a, b string) int

where

a and b are two strings that we compare.

Compare function compares the two strings lexicographically, and returns an integer. The return value would be as given in the following table

ScenarioReturn Value
a < b-1
a == b0
a > b+1

In the following example, we take two strings in a, b and compare them using Compare function.

example.go

package main

import (
	"fmt"
	"strings"
)

func main() {
	a := "Abc"
	b := "Mno"
	result := strings.Compare(a, b)
	if result == 0 {
		fmt.Println("The two strings, a and b, are equal.")
	} else if result == -1 {
		fmt.Println("String a is less than string b.")
	} else if result == 1 {
		fmt.Println("String a is greater than string b.")
	}
}

Output

String a is less than string b.

Compare strings using Comparison Operators

In the following program, we will use Comparison Operators: Equal to ==, Less than < and Greater than >; to compare strings a and b.

example.go

package main

import (
	"fmt"
)

func main() {
	a := "Abc"
	b := "Mno"
	if a == b {
		fmt.Println("The two strings, a and b, are equal.")
	} else if a < b {
		fmt.Println("String a is less than string b.")
	} else if a > b {
		fmt.Println("String a is greater than string b.")
	}
}

Output

String a is less than string b.

Conclusion

In this Golang Tutorial, we learned how to compare two strings in Go programming language, with the help of example programs.