Golang 比较两个字符串
在Go编程语言中,字符串是一种可以用于各种应用程序的数据类型之一。它是由字符组成的,并且是不可变的。在Go编程语言中,字符串在创建后无法修改。在本文中,我们将研究比较两个给定字符串的不同技术。
语法
bytes.Equal(s1,s2)
使用Equal()方法比较两个字节切片([]byte),以判断它们是否相等。如果两个字节切片相等,它会产生一个布尔值的结果(true或false),反映了这个事实。
strings.Compare(s1,s2)
Compare()函数用于按字典顺序比较两个字符串。它返回一个代表比较结果的整数值 −
如果两个字符串相等,返回值为0。
如果第一个字符串在字典顺序上小于第二个字符串,则返回值小于0。
如果第一个字符串在字典顺序上大于第二个字符串,则返回值大于0。
步骤
- 第1步 - 创建一个main包,并声明fmt(格式包)
-
第2步 - 在main函数中创建两个变量
-
第3步 - 将要比较的两个字符串赋值给它们
-
第4步 - 使用内部函数或自定义函数比较这两个字符串
-
第5步 - 打印输出
示例1
在此示例中,我们将看到如何在Golang中使用if-else语句比较两个字符串。
package main
import (
"fmt"
)
func main() {
mystr1 := "create" //create str1
fmt.Println("The string1 created here is:", mystr1)
mystr2 := "craete" //create str2
fmt.Println("The string2 created here is:", mystr2)
fmt.Println("Are the strings equal?")
if mystr1 == mystr2 {
fmt.Println("The strings are equal.") //print strings are equal
} else {
fmt.Println("The strings are not equal.") //print strings are not equal
}
}
输出
The string1 created here is: create
The string2 created here is: craete
Are the strings equal?
The strings are not equal.
示例2
在这个示例中,我们将使用bytes.Equal()函数来比较两个字符串
package main
import (
"bytes"
"fmt"
)
func main() {
mystr1 := "create" //create string1
fmt.Println("The string1 created here is:", mystr1)
mystr2 := "craete" //create string2
fmt.Println("The string2 created here is:", mystr2)
fmt.Println("Are the strings equal?")
if bytes.Equal([]byte(mystr1), []byte(mystr2)) { //use bytes.Equal() function to compare slices
fmt.Println("The strings are equal.") //print strings are not equal
} else {
fmt.Println("The strings are not equal.") //print strings are equal
}
}
输出
The string1 created here is: create
The string2 created here is: craete
Are the strings equal?
The strings are not equal.
示例3
在这个示例中,我们将使用strings.compare()函数来比较两个切片。
package main
import (
"fmt"
"strings"
)
func main() {
mystr1 := "create" //create string1
fmt.Println("The string1 created here is:", mystr1)
mystr2 := "craete" //create string2
fmt.Println("The string2 created here is:", mystr2)
fmt.Println("Are the strings equal?")
if strings.Compare(mystr1, mystr2) == 0 { //use strings.compare function
fmt.Println("The strings are equal.") //print slices are equal
} else {
fmt.Println("The strings are not equal") //print slices are not equal
}
}
输出
The string1 created here is: create
The string2 created here is: craete
Are the strings equal?
The strings are not equal
结论
我们执行了使用三种方法比较两个字符串的程序。在第一种方法中,我们使用了简单的比较运算符,在第二个示例中,我们使用了bytes.Equal()函数,而在第三个示例中,我们使用了strings.Compare()函数。