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

โปรแกรม C# นับจำนวนครั้งที่ตัวอักษรแต่ละตัวปรากฏ

นับความถี่ของแต่ละตัวอักษรในสตริง

อัลกอริทึม

  1. วนลูปตรวจสอบตัวอักษรตัวแรกของสตริง
  2. นับจำนวนครั้งที่ปรากฏในสตริงทั้งหมด
  3. ลบตัวอักษรนั้นออกจากสตริง (Replace ด้วย empty string)
  4. ทำซ้ำจนสตริงว่าง

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

using System;
public class Demo {
    public static void Main() {
        string str = "Website";
        Console.WriteLine("String: " + str);
        while (str.Length > 0) {
            Console.Write(str[0] + " = ");
            int count = 0;
            for (int j = 0; j < str.Length; j++) {
                if (str[0] == str[j]) {
                    count++;
                }
            }
            Console.WriteLine(count);
            // ลบตัวอักษรนี้ออกทั้งหมด
            str = str.Replace(str[0].ToString(), string.Empty);
        }
        Console.ReadLine();
    }
}

ผลลัพธ์

String: Website
W = 1
e = 2
b = 1
s = 1
i = 1
t = 1

วิธีที่มีประสิทธิภาพกว่า (ใช้ Dictionary):

var freq = new Dictionary();
foreach (char c in str) {
    freq[c] = freq.GetValueOrDefault(c, 0) + 1;
}