The Compare() Function is used to compare two Strings and returns :
Greater than and less than in case of Strings seems a little weird. But don't worry, we will explain it.
package main import "fmt" import "strings" func main() { x := "ab" y := "qr" z := strings.Compare(x, y) if (z == -1) { fmt.Println("First string is lower than the second String") } else if (z == 0){ fmt.Println("Both Strings are equal") } else if (z == 1){ fmt.Println("First string is greater than the second String") } }
Now, in the above example, we have taken two Strings,
And
Now, if you see the first string 'ab', it looks to be a smaller letter than the second String 'qr'(Because the letter 'a' and 'b' occurs much earlier than 'q' and 'r').
Then we use the compare method.
And since the first string is smaller than the second String. The first condition of 'if' is satisfied.
if (z == -1) { fmt.Println("First string is lower than the second String")
And the below output is printed.
Similarly in the second example,
package main import "fmt" import "strings" func main() { x := "zy" y := "ab" z := strings.Compare(x, y) if (z == -1) { fmt.Println("First string is lower than the second String") } else if (z == 0){ fmt.Println("Both Strings are equal") } else if (z == 1){ fmt.Println("First string is greater than the second String") } }
package main import "fmt" import "strings" func main() { x := "ab" y := "ab" z := strings.Compare(x, y) if (z == -1) { fmt.Println("First string is lower than the second String") } else if (z == 0){ fmt.Println("Both Strings are equal") } else if (z == 1){ fmt.Println("First string is greater than the second String") } }