Home » Comparing Strings in Golang

Comparing Strings in Golang

The strings.Compare() is a built-in function in the strings package of Golang that is used to compare two strings in lexicographical order. It returns an integer value after comparing two strings.

Syntax

The syntax for the strings.Compare() function is as follows:

func Compare(a, b string) int

Where,

  • a is the first string to compare
  • b is the second string to compare

Parameters

The strings.Compare() function takes two parameters:

  • string1: the first string to compare, of type string.
  • string2: the second string to compare, of type string.

Return Value

The strings.Compare() function returns an integer value after comparing two strings:

  • 1: if the string1 is lexicographically greater than string2 (string1 > string2)
  • 0: if the string1 is equal to string2 ( string1 == string2)
  • -1: if the string1 is lexicographically less than string2 ( string1 < string2

Let’s understand how to use the strings.Compare() function with examples.

Using strings.Compare() function to Compare Two Strings

The following go program compares two strings to check if they are equal or not using strings.Compare() function.

package main

import (
	"fmt"
	"strings"
)

func main() {
	var string1 = "golang"
	var string2 = "Golang"
	var string3 = "golang"

	// Compare string1 and string2
	fmt.Println(strings.Compare(string1, string2)) // Output: 1

	// Compare string2 and string3
	fmt.Println(strings.Compare(string2, string3)) // Output: -1

	// Compare string1 and string3
	fmt.Println(strings.Compare(string1, string3)) // Output:0

}

The output of the above comparing two strings is:

1
-1
0

In the above program, the first output returns 1 after comparing two strings as string1 (golang) is lexicographically greater than string2 (Golang). ASCII character of g is 103 and G is 071.

The second output returns -1 after comparing string2 (Golang) and string3 (golang) as string 2 is lexicographically lesser than string3.

The third output returns 0 as string1 and string3 are equal.

Conclusion

I hope the above article on comparing two strings in golang using the strings.Compare() method is helpful.

You can find more topics about the Golang tutorials on the GolangSpot Home page.

Leave a Comment