Compare strings

suggest change

Compare strings with ==, > and <

Comparison is performed on raw bytes.

This matches byte order, which is what you expect for ASCII (English letters) but not always for mixed case (“abba” is greater than “Zorro”, because 'a' > 'Z') or for other alphabets.

Compare with strings.Compare

strings.Compare has the same byte-wise result. Prefer ==, >, and <.

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 to '%s' when ignoring case\n", s1, s2)
	} else {
		fmt.Printf("'%s' is not equal '%s' when ignoring case\n", s1, s2)
	}
'gone' is equal to 'GoNe' when ignoring case

EqualFold treats both strings as UTF-8 and compares code points with 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("inconceivable! 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