阿里云-云小站(无限量代金券发放中)
【腾讯云】云服务器、云数据库、COS、CDN、短信等热卖云产品特惠抢购

简单介绍Go 字符串比较的实现示例

60次阅读
没有评论

共计 1533 个字符,预计需要花费 4 分钟才能阅读完成。

导读 本文主要介绍了 Go 字符串比较的实现示例,主要包括三种比较方式,具有一定的参考价值,感兴趣的可以了解一下

字符串比较,可以直接使用 == 进行比较,也可用用 strings.Compare 比较

go 中字符串比较有三种方式:

== 比较

strings.Compare 比较

strings.EquslFold 比较

#### 代码示例
```go
fmt.Println("go"=="go")
fmt.Println("GO"=="go")
 
fmt.Println(strings.Compare("GO","go"))
fmt.Println(strings.Compare("go","go"))
 
fmt.Println(strings.EqualFold("GO","go"))

上述代码执行结果如下:

true
false
-1
0
true
Compare 和 EqualFold 区别

EqualFold 是比较 UTF- 8 编码在小写的条件下是否相等,不区分大小写

// EqualFold reports whether s and t, interpreted as UTF-8 strings, // are equal under Unicode case-folding. func EqualFold(s, t string) bool

要注意的是 Compare 函数是区分大小写的,== 速度执行更快

// Compare is included only for symmetry with package bytes. // It is usually clearer and always faster to use the built-in // string comparison operators ==, , and so on. func Compare(a, b string) int
忽略大小写比较

有时候要忽略大小写比较, 可以使用 strings.EqualFold 字符串比较是否相等

源码实现

// EqualFold reports whether s and t, interpreted as UTF-8 strings,
// are equal under Unicode case-folding, which is a more general
// form of case-insensitivity.
func EqualFold(s, t string) bool {
    for s != ""&& t !="" {
        // Extract first rune from each string.
        var sr, tr rune
        if s[0]  x
        // or wraps around to smaller values.
        r := unicode.SimpleFold(sr)
        for r != sr && r 

通过源码可看到 if 'A' // Golang program to illustrate the // strings.EqualFold() Function package main // importing fmt and strings import ( "fmt" "strings" ) // calling main method func main() { // case insensitive comparing and returns true. fmt.Println(strings.EqualFold("Geeks", "Geeks")) // case insensitive comparing and returns true. fmt.Println(strings.EqualFold("computerscience", "computerscience")) }

 执行结构
true
true

到此这篇关于 Go 字符串比较的实现示例的文章就介绍到这了。

阿里云 2 核 2G 服务器 3M 带宽 61 元 1 年,有高配

腾讯云新客低至 82 元 / 年,老客户 99 元 / 年

代金券:在阿里云专用满减优惠券

正文完
星哥说事-微信公众号
post-qrcode
 0
星锅
版权声明:本站原创文章,由 星锅 于2024-07-25发表,共计1533字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
【腾讯云】推广者专属福利,新客户无门槛领取总价值高达2860元代金券,每种代金券限量500张,先到先得。
阿里云-最新活动爆款每日限量供应
评论(没有评论)
验证码
【腾讯云】云服务器、云数据库、COS、CDN、短信等云产品特惠热卖中