strings.Compare() Function in Golang with Examples
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:
package main
import (
"fmt"
"strings"
)
func main() {
var s1 = "Geeks"
var s2 = "GeeksforGeeks"
var s3 = "Geeks"
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:
package main
import (
"fmt"
"strings"
)
func main() {
var s1 = "apple"
var s2 = "Apple"
var s3 = "Apricot"
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’.
Last Updated :
21 Apr, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...