two strings Archives - Welcome To Golang By Example https://vikasboss.github.io/tag/two-strings/ Tue, 10 Mar 2020 18:54:19 +0000 en-US hourly 1 https://wordpress.org/?v=6.8.1 https://i0.wp.com/golangbyexamples.com/wp-content/uploads/2021/05/cropped-go_border-1.png?fit=32%2C32&ssl=1 two strings Archives - Welcome To Golang By Example https://vikasboss.github.io/tag/two-strings/ 32 32 159787465 string compare in Go (Golang) https://vikasboss.github.io/compare-two-strings-golang/ https://vikasboss.github.io/compare-two-strings-golang/#respond Tue, 10 Mar 2020 18:54:16 +0000 https://vikasboss.github.io/?p=1640 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....

The post string compare in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
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

The post string compare in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
https://vikasboss.github.io/compare-two-strings-golang/feed/ 0 1640