Compare()
Published Sep 4, 2023
Contribute to Docs
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.
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 mainimport ("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:
10-1
Codebyte Example
The following example is runnable and uses the strings.Compare()
function to compare two strings and determine their relative ordering.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.