Compare strings

suggest change

Compare strings with ==, > and <

Comparison is performed on raw bytes.

This works as you would expect for ascii (i.e. english) text but might not be what you want when strings use mixed case (e.g. “abba” is > “Zorro”) or use letters from non-english alphabets.

Compare with strings.Compare

You can also compare with strings.Compare but use ==, > and < instead as it has the same semantics.

Case-insensitive compare

Sometimes you want “Go” to equal “go”, which is not the case when using ==. You can do that using strings.EqualFold:

s1 := "gone"
s2 := "GoNe"
if strings.EqualFold(s1, s2) {
	fmt.Printf("'%s' is equal '%s' when ignoring case\n", s1, s2)
} else {
	fmt.Printf("'%s' is not equal '%s' when ignoring case\n", s1, s2)
}
'gone' is equal 'GoNe' when ignoring case

The exact rule is: both string are considered UTF-8-encoded strings and characters are compared using Unicode case-folding.

s1 := "string one"
s2 := "string two"

if s1 == s2 {
	fmt.Printf("s1 is equal to s2\n")
} else {
	fmt.Printf("s1 is not equal to s2\n")
}

if s1 == s1 {
	fmt.Printf("s1 is equal to s1\n")
} else {
	fmt.Printf("inconcivable! s1 is not equal to itself\n")
}

if s1 > s2 {
	fmt.Printf("s1 is > than s2\n")
} else {
	fmt.Printf("s1 is not > than s2\n")
}

if s1 < s2 {
	fmt.Printf("s1 is < than s2\n")
} else {
	fmt.Printf("s1 is not < than s2\n")
}
s1 is not equal to s2
s1 is equal to s1
s1 is not > than s2
s1 is < than s2

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents