ขั้นแรก ตั้งค่าสตริง -
string str = "Website";
Console.WriteLine("String: "+str); ตรวจสอบอักขระทุกตัวในสตริงและเพิ่มตัวแปรที่จะนับจำนวนการเกิดขึ้นของอักขระนั้น -
for (int j = 0; j < str.Length; j++) {
if (str[0] == str[j]) {
cal++;
}
} ตัวอย่าง
คุณสามารถลองเรียกใช้โค้ดต่อไปนี้เพื่อนับจำนวนการเกิดขึ้นของอักขระแต่ละตัวได้
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 cal = 0;
for (int j = 0; j < str.Length; j++) {
if (str[0] == str[j]) {
cal++;
}
}
Console.WriteLine(cal);
str = str.Replace(str[0].ToString(), string.Empty);
}
Console.ReadLine();
}
} ผลลัพธ์
String: Website W = 1 e = 2 b = 1 s = 1 i = 1 t = 1