Welcome To Golang By Example

Menu
  • Home
  • Blog
Menu

string compare in Go (Golang)

Posted on March 10, 2023March 10, 2023 by admin

Table of Contents

  • Overview
  • Code:

Overview

In Golang string are UTF-8 encoded. strings package of GO provides a Compare method that can be used to compare two strings in Go. Note that this method compares strings lexicographically.

Below is the signature of the function

func Compare(a, b string) int

As you can notice the return value of the Compare function is an int. This value will be

  • 0 if a==b
  • -1 if a < b
  • +1 if a > b

So if the return value is 0 then the two strings are equal. Let’s look at a working program

Code:

package main
import (
"fmt"
"strings"
)
func main() {
res := strings.Compare("abc", "abc")
fmt.Println(res)
res = strings.Compare("abc", "xyz")
fmt.Println(res)
res = strings.Compare("xyz", "abc")
fmt.Println(res)
}

Output:

0
-1
1
  • compare
  • two strings
  • Popular Articles

    Golang Comprehensive Tutorial Series

    All Design Patterns in Go (Golang)

    Slice in golang

    Variables in Go (Golang) – Complete Guide

    OOP: Inheritance in GOLANG complete guide

    Using Context Package in GO (Golang) – Complete Guide

    All data types in Golang with examples

    Understanding time and date in Go (Golang) – Complete Guide

    ©2023 Welcome To Golang By Example | Design: Web XP