Wednesday, October 16, 2024
HomeGolangHow one can evaluate strings in Go (Golang)

How one can evaluate strings in Go (Golang)



To check two strings in Go, you need to use the comparability operators ==, !=, >=, <=, <, >. Alternatively, you need to use the strings.Evaluate() operate from the strings package deal.

When evaluating strings, we imply lexicographic (alphabetical) order.

Comparability operators

Strings in Go help comparability operators ==, !=, >=, <=, <, > to match strings in lexicographic (alphabetical) order. The results of the comparability is a bool worth (true or false) indicating if the situation is met.

Instance:

package deal predominant

import "fmt"

func predominant() {
    str1 := "gosamples"
    str2 := "dev"
    str3 := "gosamples"

    fmt.Printf("%s == %s: %tn", str1, str2, str1 == str2)
    fmt.Printf("%s == %s: %tn", str1, str3, str1 == str3)
    fmt.Printf("%s != %s: %tn", str1, str2, str1 != str2)
    fmt.Printf("%s != %s: %tnn", str1, str3, str1 != str3)

    fmt.Printf("%s >= %s: %tn", str1, str2, str1 >= str2)
    fmt.Printf("%s >= %s: %tn", str1, str3, str1 >= str3)
    fmt.Printf("%s > %s: %tn", str1, str2, str1 > str2)
    fmt.Printf("%s > %s: %tnn", str1, str3, str1 > str3)

    fmt.Printf("%s <= %s: %tn", str1, str2, str1 <= str2)
    fmt.Printf("%s <= %s: %tn", str1, str3, str1 <= str3)
    fmt.Printf("%s < %s: %tn", str1, str2, str1 < str2)
    fmt.Printf("%s < %s: %tn", str1, str3, str1 < str3)
}

Output:

gosamples == dev: false
gosamples == gosamples: true
gosamples != dev: true
gosamples != gosamples: false

gosamples >= dev: true
gosamples >= gosamples: true
gosamples > dev: true
gosamples > gosamples: false

gosamples <= dev: false
gosamples <= gosamples: true
gosamples < dev: false
gosamples < gosamples: false

The strings.Evaluate() operate compares two strings in lexicographic order returning an int worth in consequence:

The result’s:

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

Instance:

package deal predominant

import (
    "fmt"
    "strings"
)

func predominant() {
    str1 := "gosamples"
    str2 := "dev"
    str3 := "gosamples"

    fmt.Printf("strings.Evaluate(%s, %s): %dn", str1, str2, strings.Evaluate(str1, str2))
    fmt.Printf("strings.Evaluate(%s, %s): %dn", str1, str3, strings.Evaluate(str1, str3))
    fmt.Printf("strings.Evaluate(%s, %s): %dn", str2, str1, strings.Evaluate(str2, str1))
}

Output:

strings.Evaluate(gosamples, dev): 1
strings.Evaluate(gosamples, gosamples): 0
strings.Evaluate(dev, gosamples): -1

Case-insensitive string comparability

If you wish to evaluate whether or not two strings are equal with out taking note of the case, you possibly can carry out a case-insensitive string comparability. Try easy methods to do it in our different tutorial.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments