Different ways to compare Strings in Golang (original) (raw)
Last Updated : 28 Oct, 2024
In Go, strings are immutable sequences of bytes encoded in UTF-8. You can compare them using **comparison operators or the strings.Compare function. In this article,we will learn different ways to compare Strings in Golang.
**Example
package main
import ( "fmt" "strings" )
func main() { s1 := "Hello" s2 := "Geeks" s3 := "Hello"
fmt.Println("String 1:", s1)
fmt.Println("String 2:", s2)
fmt.Println("String 3:", s3)}
Table of Content
Using Comparison Operators
In Go, strings can be compared with operators like ==, !=, <, >, <=, and >=. This allows checking equality or lexicographical ordering.
Syntax
// Equality and inequality str1 == str2 // true if str1 equals str2 str1 != str2 // true if str1 does not equal str2
// Lexicographical comparison str1 < str2 // true if str1 comes before str2 str1 > str2 // true if str1 comes after str2 str1 <= str2 // true if str1 comes before or is equal to str2 str1 >= str2 // true if str1 comes after or is equal to str2
**Example
Go `
package main import "fmt"
func main() { s1 := "Hello" s2 := "Geeks" s3 := "Hello"
// Equality and inequality
fmt.Println("s1 == s2:", s1 == s2) // false
fmt.Println("s1 == s3:", s1 == s3) // true
fmt.Println("s1 != s2:", s1 != s2) // true
// Lexicographical comparison
fmt.Println("s1 < s2:", s1 < s2) // true
fmt.Println("s1 > s2:", s1 > s2) // false
fmt.Println("s1 <= s3:", s1 <= s3) // true
fmt.Println("s1 >= s3:", s1 >= s3) // true}
`
Output
s1 == s2: false
s1 == s3: true
s1 != s2: true
s1 < s2: false
s1 > s2: true
s1 <= s3: true
s1 >= s3: true
Using strings.Compare Function
The strings.Compare function compares two strings lexicographically and returns:
0ifs1is equal tos21ifs1is lexicographically greater thans2-1ifs1is lexicographically less thans2
Syntax
result := strings.Compare(s1, s2)
Go `
package main import ( "fmt" "strings" ) func main() { s1 := "Hello" s2 := "Geeks" s3 := "Hello"
fmt.Println("strings.Compare(s1, s2):", strings.Compare(s1, s2)) // -1
fmt.Println("strings.Compare(s1, s3):", strings.Compare(s1, s3)) // 0
fmt.Println("strings.Compare(s2, s1):", strings.Compare(s2, s1)) // 1}
`
Output
strings.Compare(s1, s2): 1 strings.Compare(s1, s2): 0 strings.Compare(s1, s2): -1