Go Compare()

manviii_27's avatar
Published Sep 4, 2023

The strings.Compare() function is a built-in function in Golang that compares two strings lexicographically. It returns an integer value that indicates the relationship between the two strings.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn how to use Go (Golang), an open-source programming language supported by Google!
    • Beginner Friendly.
      6 hours

Syntax

strings.Compare(str1, str2)

Where str1 and str2 are the two strings to be compared:

  • If the two strings are equal, the function returns 0.
  • If the first string is lexicographically less than the second string, the function returns a negative value.
  • If the first string is lexicographically greater than the second string, the function returns a positive value.

Example

The following example demonstrates the use of the strings.Compare() function.

package main
import (
"fmt"
"strings"
)
func main() {
greater := strings.Compare("Z", "A")
equal := strings.Compare("W", "W")
lesser := strings.Compare("A", "Z")
fmt.Println(greater)
fmt.Println(equal)
fmt.Println(lesser)
}

The output will be:

1
0
-1

Codebyte Example

The following example is runnable and uses the strings.Compare() function to compare two strings and determine their relative ordering.

Code
Output

All contributors

Learn Go on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn how to use Go (Golang), an open-source programming language supported by Google!
    • Beginner Friendly.
      6 hours