如何在 Go 语言中比较两个字符串?
Go 语言内置了一个名为 Compare() 的字符串函数,我们可以使用该函数比较两个字符串。此函数使用字典序比较字符串。
语法
func Compare(a, b string) int
返回类型
- 如果字符串 (a == b),则返回 0。
- 如果字符串 (a > b),则返回 1
- 如果字符串 (a < b),则返回 -1
示例
我们考虑一下以下示例 −
package main
// importing fmt and strings
import (
"fmt"
"strings"
)
func main() {
// Intializing the variables
var a1 = "a"
var a2 = "b"
var a3 = "welcome"
var a4 = "Golang"
// using the Compare function
// a1 < a2; it will return -1
fmt.Println(strings.Compare(a1, a2))
// a2 > a1; it will return 1
fmt.Println(strings.Compare(a2, a1))
// a3 > a4; it will return 1
fmt.Println(strings.Compare(a3, a4))
// a4 < a3; it will return -1
fmt.Println(strings.Compare(a4, a3))
// a1 == a1; it will return 0
fmt.Println(strings.Compare(a1, a1))
}输出
我们考虑一下以下示例 −
-1 1 1 -1 0
示例
在此示例中,我们将使用 if 条件以及 Compare() 函数检查两个字符串是否相同。
package main
import (
"fmt"
"strings"
)
func main() {
// Intializing the variables
A := "Golang on Tutorialspoint"
B := "Golang on Tutorialspoint"
// using the Compare function
if strings.Compare(A, B) == 0 {
fmt.Println("Both the strings match.")
} else {
fmt.Println("The strings do not match.")
}
}输出
由于两个字符串相等,因此程序将生成以下输出 −
Both the strings match.
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP