หากต้องการค้นหาความถี่ของแต่ละคำในสตริง คุณสามารถลองใช้รหัสต่อไปนี้ -
ตัวอย่าง
using System;
class Demo {
static int maxCHARS = 256;
static void calculate(String s, int[] cal) {
for (int i = 0; i < s.Length; i++)
cal[s[i]]++;
}
public static void Main() {
String s = "Football!";
int []cal = new int[maxCHARS];
calculate(s, cal);
for (int i = 0; i < maxCHARS; i++)
if(cal[i] > 1) {
Console.WriteLine("Character "+(char)i);
Console.WriteLine("Occurrence = " + cal[i] + " times");
}
}
} ผลลัพธ์
Character l Occurrence = 2 times Character o Occurrence = 2 times
ด้านบน เราได้ตั้งค่าสตริงและอาร์เรย์จำนวนเต็ม ซึ่งช่วยให้เราได้รับค่าที่ซ้ำกัน วิธีการคำนวณ -
static void calculate(String s, int[] cal) {
for (int i = 0; i < s.Length; i++)
cal[s[i]]++;
} จากนั้นพิมพ์ค่าที่แสดงองค์ประกอบที่ซ้ำกันเช่นกัน -
for (int i = 0; i < maxCHARS; i++)
if(cal[i] > 1) {
Console.WriteLine("Character "+(char)i);
Console.WriteLine("Occurrence = " + cal[i] + " times");
}