Skip to content
Related Articles

Related Articles

Improve Article
strings.Compare() Function in Golang with Examples
  • Last Updated : 21 Apr, 2020

The Compare() function is an inbuilt function in the Golang programming language which is used to compare two strings. It is used to compare two strings in lexicographical order (order in which the words are arranged alphabetically, similar to the way we search words in dictionary) or to find out if the strings are equal or not. It returns an integer value as follows:

Syntax:

func Compare(s1, s2 string) int
  • Returns 0 if the strings are equal (s1==s2)
  • Returns 1 if string 1 is greater than string 2 (s1 > s2)
  • Returns -1 is string 1 is lesser than string 2 (s1 < s2)

Example 1:




// Golang program to illustrate the use of
// the strings.Compare() Function
package main
  
import (
    "fmt"
    "strings"
)
  
func main() {
  
    var s1 = "Geeks"
    var s2 = "GeeksforGeeks"
    var s3 = "Geeks"
  
    // using the function
    fmt.Println(strings.Compare(s1, s2))
    fmt.Println(strings.Compare(s2, s3))
    fmt.Println(strings.Compare(s3, s1))
  
}

Output:

-1
1
0

Explanation: The first output comes -1 as the first string is “Geeks” which is lexicographically lesser than the second string “GeeksforGeeks”. The second output comes 1 as the first string is “GeeksforGeeks” which is lexicographically greater than the second string “Geeks”. The third output comes as 0 as the first string is “Geeks” which is equal to the second string “Geeks”.



Example 2:




// Golang program to illustrate the use of
// the strings.Compare() Function
package main
  
import (
    "fmt"
    "strings"
)
  
func main() {
  
    var s1 = "apple"
    var s2 = "Apple"
    var s3 = "Apricot"
      
    // using the function
    fmt.Println(strings.Compare(s1, s2))
    fmt.Println(strings.Compare(s2, s3))
    fmt.Println(strings.Compare(s3, s1))
  
}

Output:

1
-1
-1

Explanation: The first output comes 1 as the first string is “apple” which is lexicographically greater than the second string “Apple” as the characters are compared sequentially from left to right using the Unicode Character Set and the ASCII value of ‘a’ is 97 and that of ‘A’ is 65. Therefore apple is greater than Apple.
The second output comes -1 as the first string is “Apple” which is lexicographically lesser than the second string “Apricot”. The third output comes as -1 as the first string is “Apricot” which is lexicographically lesser than the second string “apple” as ‘A’ is lesser than ‘a’.




My Personal Notes arrow_drop_up
Recommended Articles
Page :