Different ways to compare Strings in Golang
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)
}
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:
0
if s1
is equal to s2
1
if s1
is lexicographically greater than s2
-1
if s1
is lexicographically less than s2
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
Explore
Go Tutorial
3 min read
Overview
Fundamentals
Control Statements
Functions & Methods
Structure
Arrays
Slices
Strings
Pointers