C# 字符串 - GetHashCode() 方法
C# 字符串的 GetHashCode() 方法用于确定字符串的哈希码。哈希码是表示对象(例如字符串)内容的数值,常用于哈希算法和哈希表等数据结构中。
语法
以下是 C# 字符串的语法 GetHashCode() 方法 -
public override int GetHashCode ();
参数
此方法不接受任何参数。
返回值
此方法返回一个 32 位有符号整数。
示例 1:显示字符串的哈希码。
以下是使用 GetHashCode() 方法获取所有指定字符串哈希码的基本示例 -
using System; class Program { static void Main() { string str1 = "Hello"; string str2 = "tutotisldpoint"; string str3 = "India"; Console.WriteLine($"Hash code for '{str1}': {str1.GetHashCode()}"); Console.WriteLine($"Hash code for '{str2}': {str2.GetHashCode()}"); Console.WriteLine($"Hash code for '{str3}': {str3.GetHashCode()}"); } }
输出
以下是输出 -
Hash code for 'Hello': -498165893 Hash code for 'tutotisldpoint': 1462438067 Hash code for 'India': -1602197555
示例 2:在字典中使用 GetHashCode
让我们看另一个使用 GetHashCode() 方法获取字典元素哈希码的示例 -
using System; using System.Collections.Generic; class Program { static void Main() { Dictionary<int, string> hashDict = new Dictionary<int, string>(); string[] fruits = { "apple", "guava", "cherry", "banana" }; foreach (string word in fruits) { int hash = word.GetHashCode(); hashDict[hash] = word; Console.WriteLine($"Word: {word}, Hash Code: {hash}"); } int hashToFind = "banana".GetHashCode(); Console.WriteLine($"Value for hash code {hashToFind}: {hashDict[hashToFind]}"); } }
输出
以下是输出 -
The number of vowels in the string is: 5
示例 3:比较字符串的哈希码
在此示例中,我们使用 GetHashCode() 方法获取指定字符串的哈希码,并比较每个字符串的哈希码 -
using System; class Program { static void Main() { string str1 = "tutorialspoint"; string str2 = "India"; string str3 = "tutorialspoint"; // 获取字符串的哈希码 int hash1 = str1.GetHashCode(); int hash2 = str2.GetHashCode(); int hash3 = str3.GetHashCode(); Console.WriteLine($"Hash code for '{str1}': {hash1}"); Console.WriteLine($"Hash code for '{str2}': {hash2}"); Console.WriteLine($"Hash code for '{str3}': {hash3}"); // 检查哈希码是否匹配 Console.WriteLine($"Hash code of '{str1}' and '{str2}' are equal: {hash1 == hash2}"); Console.WriteLine($"Hash code of '{str1}' and '{str3}' are equal: {hash1 == hash3}"); } }
输出
以下是输出 -
Hash code for 'tutorialspoint': -246238028 Hash code for 'India': -1602197555 Hash code for 'tutorialspoint': -246238028 Hash code of 'tutorialspoint' and 'India' are equal: False Hash code of 'tutorialspoint' and 'tutorialspoint' are equal: True