Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

วิธีได้ HashCode ของสตริงใน C#

ใน C# ทุกอ็อบเจ็กต์มีเมธอด GetHashCode() ที่คืนค่า hash code เป็นจำนวนเต็ม (int) สำหรับสตริง สองสตริงที่มีค่าเท่ากันจะมี hash code เท่ากันเสมอ (แต่ hash code เท่ากันไม่ได้รับประกันว่าสตริงจะเท่ากัน เพราะอาจเกิด collision)

ตัวอย่างโค้ด

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

ข้อสังเกตสำคัญ

  • สตริงที่มีค่าเท่ากันจะมี hash code เท่ากันเสมอ
  • Hash code อาจเป็นค่าลบได้ (เช่น -1546868095)
  • Hash code อาจแตกต่างกันระหว่างการรันโปรแกรมต่างกัน (โดยเฉพาะใน .NET Core/.NET 5+ ที่ใช้ randomized hashing เพื่อความปลอดภัย)
  • อย่าใช้ hash code เป็น unique identifier เพราะอาจเกิด collision (ค่าต่างกันแต่ hash code เหมือนกัน)
  • ใช้ Equals() หรือ == เพื่อเปรียบเทียบค่าสตริงจริงๆ

การใช้งานจริง

Hash code ใช้หลักในโครงสร้างข้อมูลแบบแฮช เช่น Dictionary<TKey, TValue>, HashSet<T>, Hashtable เพื่อจัดเก็บและค้นหาข้อมูลอย่างรวดเร็ว