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

ลบคำซ้ำออกจากประโยคใน C#

ภาพรวม

ใช้ LINQ Distinct() หลังจากแยกคำด้วย Split เพื่อลบคำซ้ำ พร้อมจัดการ Case Sensitivity

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


using System;
using System.Linq;

public class Program {
    public static void Main() {
        string sentence = "One Two Three One";
        Console.WriteLine($"Original: '{sentence}'");

        // แยกคำ (split by whitespace)
        string[] words = sentence.Split(' ', StringSplitOptions.RemoveEmptyEntries);

        // ลบซ้ำ + เรียงลำดับ (Optional)
        var uniqueWords = words
            .Select(w => w.ToLower()) // Case-insensitive
            .Distinct()
            .OrderBy(w => w);

        Console.WriteLine("Unique words (lowercase, sorted):");
        Console.WriteLine(string.Join(" ", uniqueWords));
    }
}

ผลลัพธ์


Original: 'One Two Three One'
Unique words (lowercase, sorted):
one three two

รูปแบบต่างๆ

1. รักษา Case เดิม (First Occurrence)


var uniquePreserveCase = words
    .GroupBy(w => w.ToLower())
    .Select(g => g.First())
    .ToArray();

Console.WriteLine(string.Join(" ", uniquePreserveCase)); // One Two Three

2. ไม่เรียงลำดับ (Preserve Original Order)


var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var uniqueInOrder = words.Where(w => seen.Add(w.ToLower())).ToArray();
Console.WriteLine(string.Join(" ", uniqueInOrder)); // One Two Three

3. ใช้ Regex Split (รองรับ whitespace หลายแบบ)


using System.Text.RegularExpressions;

string sentence = "One   Two\tThree\nOne";
string[] words = Regex.Split(sentence, @"\s+"); // Split by any whitespace

4. นับความถี่คำ (Word Frequency)


var wordFreq = words
    .GroupBy(w => w.ToLower())
    .Select(g => new { Word = g.Key, Count = g.Count() })
    .OrderByDescending(x => x.Count);

foreach (var item in wordFreq) {
    Console.WriteLine($"{item.Word}: {item.Count}");
}

ผลลัพธ์ Word Frequency


one: 2
two: 1
three: 1

สรุป

ความต้องการวิธี
ลบซ้ำ + เรียง A-Z.Select(w => w.ToLower()).Distinct().OrderBy(w => w)
ลบซ้ำ + รักษา Case แรก.GroupBy(w => w.ToLower()).Select(g => g.First())
ลบซ้ำ + รักษาลำดับเดิมHashSet + Where(w => seen.Add(w.ToLower()))
นับความถี่.GroupBy(w => w.ToLower()).Select(g => new {Word=g.Key, Count=g.Count()})