目次
Go 言語の文字列比較メソッド
パフォーマンスの比較
##ソース コードは単純です。 Analysis
1, strings.Compare
上記の簡単な要約と分析を通じて、文字列比較には ==、>、
ホームページ バックエンド開発 Golang Go言語で文字列を比較する方法

Go言語で文字列を比較する方法

Jan 14, 2023 pm 01:06 PM
golang 言語を移動

<blockquote><p>比較方法: 1. 「==」演算子を直接使用して比較します。構文は「str1 == str2」です。この方法では大文字と小文字が区別されます。 2. strings パッケージの Compare() 関数を構文 "strings.Compare(a,b)" で使用して比較します。戻り値は int 型で、0 は 2 つの数値が等しいことを意味し、1 は a が b より大きいことを意味します。 、「-1」は a が b より小さいことを意味します。 3. 構文「strings.EqualFold(a,b)」を使用して、strings パッケージの EqualFold() 比較を使用します。 </p></blockquote> <p><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/024/63c224119dee6813.jpg" class="lazy" alt="Go言語で文字列を比較する方法" ></p> <p>このチュートリアルの動作環境: Windows 7 システム、GO バージョン 1.18、Dell G3 コンピューター。 </p> <h2 id="strong-Go-言語の文字列比較メソッド-strong"><strong>Go 言語の文字列比較メソッド</strong></h2> <p>Go 言語には 3 つの文字列比較メソッドがあります: </p> <ul class="ul-level-0"> <li> <code> ==</code>直接比較、大文字と小文字を区別します</li> <li> <code>strings.Compare(a,b)</code> この関数の戻り値は int で、0 は 2 つの数値が等しいことを意味し、1 は a>b、-1 を意味します。 a<b><li> <code>strings.EqualFold(a,b)</code> 大文字と小文字を区別せずに、等しいかどうかを直接返します。 </li></b> </li> </ul> <p>例は次のとおりです:<span style="background-color: rgb(248, 248, 248);">// 1-等号比較を使用します - 大きなメッセージを区別します</span></p> <div class="developer-code-block"><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>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 }</pre><div class="contentsignin">ログイン後にコピー</div></div></div><h2 id="strong-パフォーマンスの比較-strong"><strong>パフォーマンスの比較</strong></h2><p>次のコードは、ベンチマークを使用して簡単なパフォーマンス比較を行います。テスト プロジェクトのディレクトリ構造は次のとおりです: </p><p><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/image/916/800/564/167367265364778Go言語で文字列を比較する方法" class="lazy" title="167367265364778Go言語で文字列を比較する方法" alt="Go言語で文字列を比較する方法"/></p><p>詳細なコード: </p><div class="developer-code-block"> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>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") } }</pre><div class="contentsignin">ログイン後にコピー</div></div></div><p>テスト結果は次のとおりです。</p><p><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/image/725/103/124/1673672666716944.png" class="lazy" title="1673672666716944.png" alt="Go言語で文字列を比較する方法"/></p><p>上の図からわかるように、最も効率的なのは ==# です。 </p><h2 id="ソース-コードは単純です-Analysis-strong-strong">##ソース コードは単純です。 Analysis<strong></strong></h2><h4 id="strings-Compare-strong-strong">1, strings.Compare<strong></strong></h4><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>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 }</pre><div class="contentsignin">ログイン後にコピー</div></div><div class="developer-code-block"></div>上記のようにで、Compare は内部的に <p>= も呼び出していることがわかりました。また、この関数のコメントには、この関数はパッケージ バイトとの対称性のみを目的としていると書かれています。また、<code>==</code> と <code>></code>、<code><</code> を直接使用することをお勧めします。 <code></code></p>2, strings.EqualFold<h4 id="3.2-strings.EqualFold" name="3.2-strings.EqualFold"><strong></strong><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>// 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 &#39;A&#39; <= sr && sr <= &#39;Z&#39; && tr == sr+&#39;a&#39;-&#39;A&#39; { 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 }</pre><div class="contentsignin">ログイン後にコピー</div></div><div class="developer-code-block">この関数は、2 つの文字列を </div>utf -8## に変換する一連の操作を実行します。 # 比較時に大文字と小文字を区別せずに文字列が比較されます。 <p><code></code>要約</p> <h2 id="strong-上記の簡単な要約と分析を通じて-文字列比較には-gt-strong"><strong>上記の簡単な要約と分析を通じて、文字列比較には ==、>、</strong></h2>【関連する推奨事項: <p>Go ビデオ チュートリアル </p>、<p>プログラミング教育 <a href="http://www.php.cn/course/list/44.html" target="_blank">】</a></p> </div>

以上がGo言語で文字列を比較する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

AI Hentai Generator

AI Hentai Generator

AIヘンタイを無料で生成します。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

Golang を使用してファイルを安全に読み書きするにはどうすればよいですか? Golang を使用してファイルを安全に読み書きするにはどうすればよいですか? Jun 06, 2024 pm 05:14 PM

Go ではファイルを安全に読み書きすることが重要です。ガイドラインには以下が含まれます。 ファイル権限の確認 遅延を使用してファイルを閉じる ファイル パスの検証 コンテキスト タイムアウトの使用 これらのガイドラインに従うことで、データのセキュリティとアプリケーションの堅牢性が確保されます。

Golang データベース接続用の接続プールを構成するにはどうすればよいですか? Golang データベース接続用の接続プールを構成するにはどうすればよいですか? Jun 06, 2024 am 11:21 AM

Go データベース接続の接続プーリングを構成するにはどうすればよいですか?データベース接続を作成するには、database/sql パッケージの DB タイプを使用します。同時接続の最大数を制御するには、MaxOpenConns を設定します。アイドル状態の接続の最大数を設定するには、ConnMaxLifetime を設定します。

GolangでJSONデータをデータベースに保存するにはどうすればよいですか? GolangでJSONデータをデータベースに保存するにはどうすればよいですか? Jun 06, 2024 am 11:24 AM

JSON データは、gjson ライブラリまたは json.Unmarshal 関数を使用して MySQL データベースに保存できます。 gjson ライブラリは、JSON フィールドを解析するための便利なメソッドを提供します。json.Unmarshal 関数には、JSON データをアンマーシャリングするためのターゲット型ポインターが必要です。どちらの方法でも、SQL ステートメントを準備し、データをデータベースに永続化するために挿入操作を実行する必要があります。

Golang フレームワークと Go フレームワーク: 内部アーキテクチャと外部機能の比較 Golang フレームワークと Go フレームワーク: 内部アーキテクチャと外部機能の比較 Jun 06, 2024 pm 12:37 PM

GoLang フレームワークと Go フレームワークの違いは、内部アーキテクチャと外部機能に反映されています。 GoLang フレームワークは Go 標準ライブラリに基づいてその機能を拡張していますが、Go フレームワークは特定の目的を達成するための独立したライブラリで構成されています。 GoLang フレームワークはより柔軟であり、Go フレームワークは使いやすいです。 GoLang フレームワークはパフォーマンスの点でわずかに優れており、Go フレームワークはよりスケーラブルです。ケース: gin-gonic (Go フレームワーク) は REST API の構築に使用され、Echo (GoLang フレームワーク) は Web アプリケーションの構築に使用されます。

クラウドネイティブ開発における golang フレームワークの役割と利点 クラウドネイティブ開発における golang フレームワークの役割と利点 Jun 06, 2024 am 11:32 AM

Go フレームワークは、マイクロサービスの構築、クラウド機能のデプロイ、コンテナ オーケストレーション、データ ストリーム処理など、クラウド ネイティブ開発において重要な役割を果たします。その利点は、高性能、拡張性、堅牢性、および豊富なエコシステムです。さらに、Go フレームワークの実際のケースでは、Gin フレームワークを使用すると、「Hello, CloudFunctions!」というメッセージでクラウド関数を簡単に構築およびデプロイできます。

Golang フレームワークを使用する際に注意する必要がある一般的な点は何ですか? Golang フレームワークを使用する際に注意する必要がある一般的な点は何ですか? Jun 06, 2024 pm 01:33 PM

Golang フレームワークを使用する場合は、ルーティング エラーを避けるために、ルートがリクエストと一致するかどうかを確認する必要があります。パフォーマンスの低下を避けるために、ミドルウェアは注意して使用してください。データベース接続を適切に管理して、パフォーマンスの問題やクラッシュを防ぎます。エラー ラッパーを使用してエラーを処理し、コードが明確でデバッグしやすいようにします。信頼できるソースからサードパーティのパッケージを入手し、パッケージを最新の状態に保ちます。

Golang で HTTP リダイレクトを処理するにはどうすればよいですか? Golang で HTTP リダイレクトを処理するにはどうすればよいですか? Jun 06, 2024 am 11:46 AM

Go で HTTP リダイレクトを処理するときは、次のリダイレクト タイプを理解する必要があります。 301 Move Permanent 302 Found 303 View Others リダイレクトは、net/http パッケージの http.Client タイプと Do メソッド、およびカスタム CheckRedirect 関数を通じて処理できます。リダイレクトを追跡します。

Golang フレームワーク開発実践チュートリアル: FAQ Golang フレームワーク開発実践チュートリアル: FAQ Jun 06, 2024 am 11:02 AM

Go フレームワーク開発 F​​AQ: フレームワークの選択: アプリケーションの要件と開発者の好み (Gin (API)、Echo (拡張可能)、Beego (ORM)、Iris (パフォーマンス) など) によって異なります。インストールと使用: gomod コマンドを使用して、フレームワークをインストールし、インポートして使用します。データベース対話: gorm などの ORM ライブラリを使用して、データベース接続と操作を確立します。認証と認可: gin-contrib/sessions などのセッション管理および認証ミドルウェアを使用します。実際のケース: Pin フレームワークを使用して、POST、GET、その他の関数を提供する単純なブログ API を構築します。

See all articles