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

ลบอักขระซ้ำทั้งหมดจากสตริงใน C#

ใช้ HashSet<char> เพื่อจัดเก็บอักขระที่ไม่ซ้ำกัน เนื่องจาก HashSet ไม่อนุญาตให้มีค่าซ้ำ

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

using System;
using System.Collections.Generic;

namespace Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = "ppqqrr";
            Console.WriteLine("Initial String: " + str);
            
            var res = new HashSet(str);
            Console.Write("New String after removing duplicates: ");
            foreach (char c in res) Console.Write(c);
        }
    }
}

ผลลัพธ์

Initial String: ppqqrr
New String after removing duplicates: pqr

หมายเหตุ: ลำดับอักขระในผลลัพธ์อาจไม่เหมือนเดิม เพราะ HashSet ไม่รับประกันลำดับ หากต้องการรักษาลำดับ ให้ใช้ Distinct() ของ LINQ หรือ Loop ตรวจสอบเอง