Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Xóa từ trùng lặp trong câu C#

Xóa từ trùng lặp trong chuỗi: tách từ (Split), dùng Distinct (LINQ) hoặc HashSet, sau đó ghép lại.

Ví dụ minh họa

using System;
using System.Linq;

class Program
{
    static void Main()
    {
        string sentence = "One Two Three One Two";
        Console.WriteLine($"Gốc: {sentence}");
        
        // Cách 1: LINQ Distinct (giữ thứ tự xuất hiện đầu tiên)
        var words = sentence.Split(' ', StringSplitOptions.RemoveEmptyEntries);
        var distinctWords = words.Distinct(); // Mặc định so sánh ordinal, case-sensitive
        string result1 = string.Join(" ", distinctWords);
        Console.WriteLine($"Distinct: {result1}");
        
        // Cách 2: HashSet (không giữ thứ tự)
        var hashSet = new System.Collections.Generic.HashSet(words);
        string result2 = string.Join(" ", hashSet);
        Console.WriteLine($"HashSet: {result2}");
        
        // Cách 3: Distinct không phân biệt hoa/thường
        var distinctIgnoreCase = words.Distinct(StringComparer.OrdinalIgnoreCase);
        string result3 = string.Join(" ", distinctIgnoreCase);
        Console.WriteLine($"Distinct IgnoreCase: {result3}");
    }
}

Kết quả đầu ra

Gốc: One Two Three One Two
Distinct: One Two Three
HashSet: Three One Two
Distinct IgnoreCase: One Two Three

Lưu ý: Code gốc dùng orderby làm thay đổi thứ tự từ. Distinct() giữ thứ tự xuất hiện đầu tiên. Dùng StringSplitOptions.RemoveEmptyEntries để bỏ qua khoảng trắng thừa.