Loading, please wait...

A to Z Full Forms and Acronyms

Explain different ways to compare Strings in GoLang | Go Programming Tutorial

Nov 20, 2022 #GoProgramming #GoLanguage, 1291 Views
In this article, you will learn about the different ways to compare Strings in Go Programming Language. 

Explain different ways to compare Strings in GoLang | Go Programming Tutorial

In this article, you will learn about the different ways to compare Strings in Go Programming Language. 

In GoLang, the string is an immutable chain of random bytes with UTF-8 encoding. The user will compare the strings with each other using two different ways:

1. Using comparison operators: Go strings support all the comparison operators, i.e, ==, !=, >=, <=, <,>. Here, the two operators == and != are used to check if the current strings are equal or not, and >=, <=, <,> operators are used to find the lexical order. The return type of these operators is boolean, which means if the condition is satisfied, it will return true, otherwise false.Example:

package main
import "fmt"
 
// Main function
func main() {
 
    // Create and initialize strings
    // with the help of shorthand declaration
    str1 := "Tutorials"
    str2 := "Link"
    str3 := "TutorialsLink"
 
    // Checking the string are equal
    result1 := str1 == str2
    result2 := str2 == str3
    result3 := str3 == str1
     
    fmt.Println("Result 1: ", result1)
    fmt.Println("Result 2: ", result2)
    fmt.Println("Result 3: ", result3)
 
    // Checking the string are not equalusing != operator
    result4 := str1 != str2
    result5 := str2 != str3
    result6 := str3 != str1
     
    fmt.Println("\nResult 4: ", result4)
    fmt.Println("Result 5: ", result5)
    fmt.Println("Result 6: ", result6)
 
}
Output:
Result 1: False
Result 2: False
Result 3: False
 
Result 4: True
Result 5: True
Result 6: True

2. Using Compare() method: The user can compare two strings using the built-in function compare provided by the strings package. The function returns an integer value after comparing two strings. The return values are:

  • Return 0, if str1 == str2
  • Return 1, if str1> str2.
  • Return -1, if str1< str2

Example:

package main
 
import (
    "fmt"
    "strings"
)
 
func main() {
 
    // Compare string using Compare()
    fmt.Println(strings.Compare("Tutorials", "Link"))
     
    fmt.Println(strings.Compare("TutorialsLink",
                               "TutorialsLink"))
     
    fmt.Println(strings.Compare("Links", " LINK"))
}
Output:
False
True
False
A to Z Full Forms and Acronyms