How can we compare strings in Golang?

In Golang, you can use the strings.Compare function to compare the sizes of two strings.

Grammar:

func Compare(a, b string) int

Parameter.

  1. a: the first string to be compared
  2. b: the second string to be compared

Return value:

  1. If a is less than b, return a negative integer.
  2. Return 0 if a is equal to b.
  3. If a is greater than b, return a positive integer.

Example code:

package main

import (
	"fmt"
	"strings"
)

func main() {
	a := "hello"
	b := "world"
	c := "hello"

	fmt.Println(strings.Compare(a, b)) // 输出 -1
	fmt.Println(strings.Compare(a, c)) // 输出 0
	fmt.Println(strings.Compare(b, a)) // 输出 1
}

In the example above, string a is less than string b, so the Compare function returns -1. String a is equal to string c, so it returns 0. String b is greater than string a, so it returns 1.

bannerAds