How to compare two strings in Golang?


Golang has a built-in string function called Compare() that we can use to compare two strings. Here strings are compared using the lexicographical order.

Syntax

func Compare(a, b string) int

Return Types

  • If the strings (a == b), it returns 0.
  • If the strings (a > b), then it returns 1
  • If the strings (a < b), then it returns -1

Example

Let us consider the following example −

package main
// importing fmt and strings
import (
   "fmt"
   "strings"
)
func main() {
   // Intializing the variables
   var a1 = "a"
   var a2 = "b"
   var a3 = "welcome"
   var a4 = "Golang"
   
   // using the Compare function
   // a1 < a2; it will return -1
   fmt.Println(strings.Compare(a1, a2))
   
   // a2 > a1; it will return 1
   fmt.Println(strings.Compare(a2, a1))
   
   // a3 > a4; it will return 1
   fmt.Println(strings.Compare(a3, a4))
   
   // a4 < a3; it will return -1
   fmt.Println(strings.Compare(a4, a3))
   
   // a1 == a1; it will return 0
   fmt.Println(strings.Compare(a1, a1))
}

Output

Let us consider the following example −

-1
1
1
-1
0

Example

In this example, we are going to use an if condition along with the Compare() function to check whether the two strings are same or not.

package main
import (
   "fmt"
   "strings"
)
func main() {
   // Intializing the variables
   A := "Golang on Tutorialspoint"
   B := "Golang on Tutorialspoint"
   
   // using the Compare function
   if strings.Compare(A, B) == 0 {
      fmt.Println("Both the strings match.")
   } else {
      fmt.Println("The strings do not match.")
   }
}

Output

As both the strings are equal, the program will generate the following output −

Both the strings match.

Updated on: 10-Mar-2022

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements