How to compare strings in go language

青灯夜游
Release: 2023-01-14 13:06:28
Original
4667 people have browsed it

Comparison method: 1. Directly use the "==" operator to compare, the syntax is "str1 == str2", this method is case-sensitive. 2. Compare using the Compare() function of the strings package, with the syntax "strings.Compare(a,b)"; the return value is int type, 0 means the two numbers are equal, 1 means a is greater than b, and "-1" means a is less than b. . 3. Use the EqualFold() comparison of the strings package, with the syntax "strings.EqualFold(a,b)".

How to compare strings in go language

The operating environment of this tutorial: Windows 7 system, GO version 1.18, Dell G3 computer.

Go language string comparison methods

There are three string comparison methods in go language:

  • == Direct comparison, case sensitive
  • strings.Compare(a,b) The return value of this function is int, 0 means the two numbers are equal, 1 means a>b, -1 means a
  • strings.EqualFold(a,b) Directly returns whether they are equal, not case-sensitive.

Examples are as follows:// 1-Use equal sign comparison - distinguish large messages

func Equal(s1, s2 string) bool { return s1 == s2 } // 2-使用 compare 比较——区分大小写 func Compare(s1, s2 string) bool { return strings.Compare(s1, s2) == 0 // } //3-EqualFold 比较——不区分大小写. case-fold 即大小写同一处理 func EqualFold(s1, s2 string) bool { return strings.EqualFold(s1, s2) } // 使用等号比较——忽略大小写 func Equal2(s1, s2 string) bool { return strings.ToLower(s1) == strings.ToLower(s2) } // 使用 compare 比较——不区分大小写 func Compare2(s1, s2 string) bool { return strings.Compare(strings.ToLower(s1), strings.ToLower(s2)) == 0 } func StringCompareTest() { fmt.Println("== 区分大小写", Equal("go", "Go")) //false fmt.Println("== 忽略大小写",Equal2("go", "Go")) //true fmt.Println("compare 区分大小写",Compare("go", "Go")) //false fmt.Println("compare 忽略大小写",Compare2("go", "Go")) //true fmt.Println("EqualFold 忽略大小写",EqualFold("go", "Go")) // true }
Copy after login

Performance comparison

The following code uses Benchmark to do a simple performance comparison. The directory structure of the test project is:

How to compare strings in go language

Detailed code:

package test import ( "../str" "testing" ) func BenchmarkStrEqual(b *testing.B) { for i := 0; i < b.N; i++ { str.Equal("go", "Go") } } func BenchmarkStrEqual2(b *testing.B) { for i := 0; i < b.N; i++ { str.Equal2("go", "Go") } } func BenchmarkStrCompare(b *testing.B) { for i := 0; i < b.N; i++ { str.Compare("go", "Go") } } func BenchmarkStrCompare2(b *testing.B) { for i := 0; i < b.N; i++ { str.Compare2("go", "Go") } } func BenchmarkStrEqualFold(b *testing.B) { for i := 0; i < b.N; i++ { str.EqualFold("go", "Go") } }
Copy after login

The test results are as follows:

How to compare strings in go language

As can be seen from the above figure, the most efficient one is ==

The source code is simple Analysis

1, strings.Compare

package strings // 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. // // 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 }
Copy after login

As shown above, we found that Compare also calls = internally =, and the comment of this function also says that this function is only for symmetry with package bytes. And it is recommended that we use == and >, < directly.

2, 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] < utf8.RuneSelf { sr, s = rune(s[0]), s[1:] } else { r, size := utf8.DecodeRuneInString(s) sr, s = r, s[size:] } if t[0] < utf8.RuneSelf { tr, t = rune(t[0]), t[1:] } else { r, size := utf8.DecodeRuneInString(t) tr, t = r, 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 } // One string is empty. Are both? return s == t }
Copy after login

This function performs a series of operations to convert two strings into utf -8 Strings are compared, ignoring case when comparing.

Summary

Through the above simple summary and analysis, we found that for string comparison, it is better to directly use the ==, >,

【Related recommendations: Go video tutorial, Programming teaching

The above is the detailed content of How to compare strings in go language. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!