Menu Close

Go – How to compare two strings in go golang ?

Here, We are going to learn about comparing two strings in go golang. We can compare two strings in go by using Compare() function of strings package in go golang.

Function proto type:

func Compare(a, b string) int

Return value:

Compare() function returns an integer value by comparing two strings lexicographically.

It returns 0 if a == b, -1 if a < b, and +1 if a > b.

Compare() function is included only for symmetry with package bytes and It is usually clearer and always faster to use the built-in string comparison operators ==, <, >, and so on.

Example:

package main

import (
	"fmt"
	"strings"
)

func main() {

	fmt.Println(strings.Compare("Hello", "Hi"))

	fmt.Println(strings.Compare("Hello", "Hello"))

	fmt.Println(strings.Compare("Hi", "Hello"))

}

Output:

-1
0
1

To learn more about golang, Please refer given below link.

https://techieindoor.com/go-lang-tutorial/

References:

https://golang.org/doc/
https://golang.org/pkg/
https://golang.org/pkg/strings/
Posted in golang, packages, strings

Leave a Reply

Your email address will not be published. Required fields are marked *