How to compare two string values in Go in a case insensitive manner?

huangapple go评论63阅读模式
英文:

How to compare two string values in Go in a case insensitive manner?

问题

如何进行不区分大小写的字符串比较?
例如:"a" == "a""a" == "A" 都应返回 true

英文:

How to compare two strings with case insensitivity?
For example: Both "a" == "a" and "a" == "A" must return true.

答案1

得分: 27

有一个strings.EqualFold()函数可以执行不区分大小写的字符串比较。

例如:

fmt.Println(strings.EqualFold("aa", "Aa"))
fmt.Println(strings.EqualFold("aa", "AA"))
fmt.Println(strings.EqualFold("aa", "Ab"))

输出结果(在Go Playground上尝试):

true
true
false
英文:

There is a strings.EqualFold() function which performs case insensitive string comparison.

For example:

fmt.Println(strings.EqualFold("aa", "Aa"))
fmt.Println(strings.EqualFold("aa", "AA"))
fmt.Println(strings.EqualFold("aa", "Ab"))

Output (try it on the Go Playground):

true
true
false

答案2

得分: -1

找到答案了。将两个字符串转换为小写或大写,并进行比较。

import "strings"
strings.ToUpper(str1) == strings.ToUpper(str2)
英文:

Found the answer. Convert both strings to either lowercase or upper case and compare.
<code>
import "strings"
strings.ToUpper(str1) == strings.ToUpper(str2)
</code>

答案3

得分: -2

strings.EqualFold()不是用于比较,有时候你需要比较的标志。

func compareNoCase(i, j string) int {
    is, js := []rune(i), []rune(j)
    il, jl := len(is), len(js)

    ml := il
    if ml > jl {
        ml = jl
    }

    for n := 0; n < ml; n++ {
        ir, jr := unicode.ToLower(is[n]), unicode.ToLower(js[n])
        if ir < jr {
            return -1
        } else if ir > jr {
            return 1
        }
    }

    if il < jl {
        return -1
    }
    if il > jl {
        return 1
    }
    return 0
}

func equalsNoCase(i, j string) bool {
    return compareNoCase(i, j) == 0
}

以上是要翻译的内容。

英文:

strings.EqualFold() is not compare, some times you need sign of compare

func compareNoCase(i, j string) int {
	is, js := []rune(i), []rune(j)
	il, jl := len(is), len(js)

  ml := il
	if ml &gt; jl {
		ml = jl
	}

	for n := 0; n &lt; ml; n++ {
		ir, jr := unicode.ToLower(is[n]), unicode.ToLower(js[n])
		if ir &lt; jr {
			return -1
		} else if ir &gt; jr {
			return 1
		}
	}
  
	if il &lt; jl {
		return -1
	}
	if il &gt; jl {
		return 1
	}
	return 0
}

func equalsNoCase(i, j string) bool {
	return compareNoCase(i, j) == 0
}

huangapple
  • 本文由 发表于 2017年5月18日 07:46:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/44036426.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定