How to determine string equality in Golang?
In Golang, determining whether two strings are equal is a common operation. In this article, we will introduce several commonly used methods to determine whether two strings are equal and give corresponding code examples.
==
operatorThe simplest way is to use the==
operator to determine whether two strings are equal . An example is as follows:
package main import "fmt" func main() { str1 := "Hello" str2 := "Hello" if str1 == str2 { fmt.Println("str1 和 str2 相等") } else { fmt.Println("str1 和 str2 不相等") } }
In the above example, we created two stringsstr1
andstr2
and then used the==
operation symbol to compare whether they are equal. If they are equal, output "str1 and str2 are equal", otherwise output "str1 and str2 are not equal".
strings.EqualFold
functionIn addition to using the==
operator, we can also usestrings.EqualFold
Function to determine whether two strings are equal. This function compares two strings regardless of case. An example is as follows:
package main import ( "fmt" "strings" ) func main() { str1 := "Hello" str2 := "hello" if strings.EqualFold(str1, str2) { fmt.Println("str1 和 str2 相等") } else { fmt.Println("str1 和 str2 不相等") } }
In the above example, we use thestrings.EqualFold
function to compare whetherstr1
andstr2
are equal. The function ignores case, so the output is "str1 and str2 are equal".
strings.Compare
functionAnother method is to use thestrings.Compare
function to compare the sizes of two strings . If the two strings are equal, the function returns 0. The example is as follows:
package main import ( "fmt" "strings" ) func main() { str1 := "Hello" str2 := "Hello" result := strings.Compare(str1, str2) if result == 0 { fmt.Println("str1 和 str2 相等") } else { fmt.Println("str1 和 str2 不相等") } }
In the above example, we use thestrings.Compare
function to compare whetherstr1
andstr2
are equal. The strings are equal, so the output result is "str1 and str2 are equal".
Through the above methods, we can easily determine whether two strings are equal in Golang. Choosing the appropriate method can be determined based on specific needs to achieve the best judgment.
The above is the detailed content of How to determine string equality in Golang?. For more information, please follow other related articles on the PHP Chinese website!