English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Go言語では、文字列はUTF-8エンコードされた不可変な任意のバイトのリンク。文字列を比較するには、以下の2つの異なる方法を使用できます:
1.比較演算子の使用:文字列が比較演算子をサポートするに移動します、つまり==、!=、> =、<=、<、>。ここでは、==および!=演算子は、指定された文字列が等しいかどうかを確認するために使用されます。および> =、<=、<、>演算子は、文法的順序を検索するために使用されます。これらの演算子の結果はボルン型であり、条件が満たされると返されますtrue、それ以外の場合は返しますfalse。
文字列の==と!=演算子の例1:
//文字列の==と!=演算子 package main import "fmt" func main() { //文字の作成と初期化 //簡略宣言を使用して str1 := "Geeks" str2 := "Geek" str3 := "w3codebox" str4 := "Geeks" //文字列が相等かどうかを確認します //使用==演算子 result1 := str1 == str2 result2 := str2 == str3 result3 := str3 == str4 result4 := str1 == str4 fmt.Println("Result 1: ", result1) fmt.Println("Result 2: ", result2) fmt.Println("Result 3: ", result3) fmt.Println("Result 4: ", result4) //文字列が不相等かどうかを確認します //使用!=演算子 result5 := str1 != str2 result6 := str2 != str3 result7 := str3 != str4 result8 := str1 != str4 fmt.Println("\nResult 5: ", result5) fmt.Println("Result 6: ", result6) fmt.Println("Result 7: ", result7) fmt.Println("Result 8: ", result8) }
出力:
Result 1: false Result 2: false Result 3: false Result 4: true Result 5: true Result 6: true Result 7: true Result 8: false
文字列の比較演算子の例2:
//文字列の比較演算子 package main import "fmt" func main() { //作成および初期化 //短縮宣言を使用して myslice := []string{"Geeks", "Geeks", "gfg", "GFG", "for"} fmt.Println("Slice: ", myslice) //比較演算子を使用して result1 := "GFG" > "Geeks" fmt.Println("Result 1: ", result1) result2 := "GFG" < "Geeks" fmt.Println("Result 2: ", result2) result3 := "Geeks" >= "for" fmt.Println("Result 3: ", result3) result4 := "Geeks" <= "for" fmt.Println("Result 4: ", result4) result5 := "Geeks" == "Geeks" fmt.Println("Result 5: ", result5) result6 := "Geeks" != "for" fmt.Println("Result 6: ", result6) }
出力:
Slice: [Geeks Geeks gfg GFG for] Result 1: false Result 2: true Result 3: false Result 4: true Result 5: true Result 6: true
2.使用Compare()メソッド:さらに、stringsパッケージが提供するビルトイン関数Compare()を使用して、2つの文字列を比較することもできます。この関数は比較の結果、整数値を返します。返される値は:
もしstr1 == str2、0を返します。
もしstr1> str2、返します1 。
もしstr1 <str2、返します-1 。
语法:
func Compare(str1, str2 string) int
//文字列はcompare()関数を使用して比較します package main import ( "fmt" "strings" ) func main() { //文字列を比較するための比較関数を使用します fmt.Println(strings.Compare("gfg", "Geeks")) fmt.Println(strings.Compare("w3codebox", "w3codebox")) fmt.Println(strings.Compare("Geeks", " GFG")) fmt.Println(strings.Compare("GeeKS", "GeeKs")) }
出力:
1 0 1 -1