如何獲取 C# 中字串的 HashCode?


要獲取字串的 HashCode,程式碼如下,程式碼如下 −

示例

 動態演示

using System;
public class Demo {
   public static void Main(String[] args) {
      string str1 = "Akon";
      string str2 = "Eminem";
      Console.WriteLine("String 1 = "+str1);
      Console.WriteLine("HashCode of String 1 = "+str1.GetHashCode());
      Console.WriteLine("String 2 = "+str2);
      Console.WriteLine("HashCode of String 2 = "+str2.GetHashCode());
      Console.WriteLine("String 1 is equal to String 2: {0}", str1.Equals(str2));
   }
}

輸出

這將產生以下輸出 −

String 1 = Akon
HashCode of String 1 = 416613838
String 2 = Eminem
HashCode of String 2 = 40371907
String 1 is equal to String 2: False

示例

讓我們看另一個例子 −

 動態演示

using System;
public class Demo {
   public static void Main(String[] args) {
      string str1 = "Imagine Dragons";
      string str2 = "Imagine Dragons";
      Console.WriteLine("String 1 = "+str1);
      Console.WriteLine("HashCode of String 1 = "+str1.GetHashCode());
      Console.WriteLine("String 2 = "+str2);
      Console.WriteLine("HashCode of String 2 = "+str2.GetHashCode());
      Console.WriteLine("String 1 is equal to String 2: {0}", str1.Equals(str2));
   }
}

輸出

這將產生以下輸出 −

String 1 = Imagine Dragons
HashCode of String 1 = -1546868095
String 2 = Imagine Dragons
HashCode of String 2 = -1546868095
String 1 is equal to String 2: True

更新於: 06-Dec-2019

194 次瀏覽

開始你的 職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.