[Go]字符串 比较

比较方式

  1. == 区分大小写,效率最高
  2. strings.Compare (a, b string) int 区分大小写,按字典序比较两个字符串(a == b 则 0;a < b 则 -1;a > b 则 +1)
  3. strings.EqualFold (s, t string) bool不区分大小写

示例

golang 复制代码
//比较的字符串及其结果

fmt.Println("go" == "go") // true
fmt.Println("go" == "Go") // false

fmt.Println(strings.Compare("go", "go")) // 0
fmt.Println(strings.Compare("go", "golang")) //-1

fmt.Println(strings.EqualFold("go", "Go")) // true

源码

strings.Compare

golang 复制代码
/*
    strings/compare.go
*/
// Compare returns an integer comparing two strings lexicographically.
// The result will be 0 if a == b, -1 if a < b, and +1 if a > b.
//
// Use Compare when you need to perform a three-way comparison (with
// [slices.SortFunc], for example). It is usually clearer and always faster
// to use the built-in string comparison operators ==, <, >, and so on.
// Compare 按字典序比较两个字符串,并返回一个整数。
// 若 a == b,返回 0;若 a < b,返回 -1;若 a > b,返回 1。
//
// 当你需要执行三元比较时使用该函数(例如配合 [slices.SortFunc] 切片排序函数使用)。
// 通常情况下,使用 Go 内置的字符串比较运算符 ==、<、> 等,代码更清晰、执行速度也更快。
func Compare(a, b string) int {
	return bytealg.CompareString(a, b)
}

/*
    internal/bytealg/compare_native.go
*/
func CompareString(a, b string) int {
	return abigen_runtime_cmpstring(a, b)
}

// The declaration below generates ABI wrappers for functions
// implemented in assembly in this package but declared in another package.
// 下方的声明为函数生成 ABI 包装器,
// 这些函数在本包中用汇编实现,但在另一个包中声明。


//go:linkname abigen_runtime_cmpstring runtime.cmpstring
func abigen_runtime_cmpstring(a, b string) int

/*
    如amd64
    https://go.dev/src/internal/bytealg/compare_amd64.s
    
*/

go.dev/src/interna...

strings.EqualFold

golang 复制代码
// EqualFold reports whether s and t, interpreted as UTF-8 strings,
// are equal under simple Unicode case-folding, which is a more general
// form of case-insensitivity.
//EqualFold 用于判断将 s 和 t 解释为 UTF-8 字符串时,在简单 Unicode 大小写折叠规则下是否相等 ------ 这是一种更通用的不区分大小写的形式。
func EqualFold(s, t string) bool {
	// ASCII fast path
	i := 0
	for n := min(len(s), len(t)); i < n; i++ {
		sr := s[i]
		tr := t[i]
		if sr|tr >= utf8.RuneSelf {
			goto hasUnicode
		}

		// Easy case.
		if tr == sr {
			continue
		}

		// Make sr < tr to simplify what follows.
		if tr < sr {
			tr, sr = sr, tr
		}
		// ASCII only, sr/tr must be upper/lower case
		if 'A' <= sr && sr <= 'Z' && tr == sr+'a'-'A' {
			continue
		}
		return false
	}
	// Check if we've exhausted both strings.
	return len(s) == len(t)

hasUnicode:
	s = s[i:]
	t = t[i:]
	for _, sr := range s {
		// If t is exhausted the strings are not equal.
		if len(t) == 0 {
			return false
		}

		// Extract first rune from second string.
		tr, size := utf8.DecodeRuneInString(t)
		t = t[size:]

		// If they match, keep going; if not, return false.

		// Easy case.
		if tr == sr {
			continue
		}

		// Make sr < tr to simplify what follows.
		if tr < sr {
			tr, sr = sr, tr
		}
		// Fast check for ASCII.
		if tr < utf8.RuneSelf {
			// ASCII only, sr/tr must be upper/lower case
			if 'A' <= sr && sr <= 'Z' && tr == sr+'a'-'A' {
				continue
			}
			return false
		}

		// General case. SimpleFold(x) returns the next equivalent rune > x
		// or wraps around to smaller values.
		r := unicode.SimpleFold(sr)
		for r != sr && r < tr {
			r = unicode.SimpleFold(r)
		}
		if r == tr {
			continue
		}
		return false
	}

	// First string is empty, so check if the second one is also empty.
	return len(t) == 0
}
相关推荐
小满zs13 分钟前
Go语言第二十一章(Gin上传文件)
后端·go
我不会起名字3226 小时前
Agent 总调错工具?MCP 接进 Go 后端的 4 个约束
后端·go·agent·mcp
我不会起名字3222 天前
WebSocket 停机与在线状态:Shutdown 返回后还需要清理什么
redis·后端·websocket·go·即时通讯·im·故障排查
小满zs3 天前
Go语言第二十章(初探Gin)
后端·go
小满zs3 天前
Go语言第十九章(http标准库)
后端·go
我不会起名字3224 天前
仅 Web 主动 ping:30 秒读超时与各平台保活
前端·后端·websocket·go·即时通讯·im·故障排查
星星在线4 天前
Go + gRPC 插件式服务框架 —— 技术实现与分析
go
Java码农也是农4 天前
一篇文章讲清 Go 并发:goroutine、channel、select 与取消
go·并发编程·context·channel·goroutine
afumu4 天前
Go 写一个只监听 127.0.0.1 的控制服务:鉴权、白名单、危险命令拦截
后端·安全·go
我不会起名字3224 天前
未接入最终读上限的参数:`websocketMaxMsgLen` 与 12.5 倍差距
后端·websocket·go·即时通讯·im·故障排查