比较方法:1、直接使用“==”运算符比较,语法“str1 == str2”,该方法区分大小写。2、利用strings包的Compare()函数比较,语法“strings.Compare(a,b)”;返回值为int类型,0表示两数相等,1表示a大于b,“-1”表示a小于b。3、利用strings包的EqualFold()比较,语法“strings.EqualFold(a,b)”。
本教程操作环境:windows7系统、GO 1.18版本、Dell G3电脑。
Go语言比较字符串方式在 go 语言中字符串比较的方式有如下三种:
== 直接比较,区分大小写strings.Compare(a,b) 该函数返回值为 int, 0 表示两数相等,1 表示 a>b, -1 表示 a b. // // 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 { // NOTE(rsc): This function does NOT call the runtime cmpstring function, // because we do not want to provide any performance justification for // using strings.Compare. Basically no one should use strings.Compare. // As the comment above says, it is here only for symmetry with package bytes. // If performance is important, the compiler should be changed to recognize // the pattern so that all code doing three-way comparisons, not just code // using strings.Compare, can benefit. if a == b { return 0 } if a < b { return -1 } return +1 }登录后复制如上所示,我们发现,Compare 内部也是调用了 == , 而且该函数的注释中也说了,这个函数 only for symmetry with package bytes。而且推荐我们直接使用 == 和 >、