วนลูปนับจำนวนตัวอักษรด้วยอาร์เรย์:
for (int i = 0; i < s.Length; i++)
a[s[i]]++;
กำหนดค่า:
String s = "livelife!"; int[] a = new int[maxCHARS];
แสดงผลตัวอักษรที่ปรากฏมากกว่า 1 ครั้ง:
for (int i = 0; i < maxCHARS; i++)
if (a[i] > 1) {
Console.WriteLine("Character " + (char)i);
Console.WriteLine("Occurrence = " + a[i] + " times");
}
ตัวอย่าง
using System;
class Program {
static int maxCHARS = 256;
static void display(String s, int[] a) {
for (int i = 0; i < s.Length; i++)
a[s[i]]++;
}
public static void Main() {
String s = "livelife!";
int[] a = new int[maxCHARS];
display(s, a);
for (int i = 0; i < maxCHARS; i++)
if (a[i] > 1) {
Console.WriteLine("Character " + (char)i);
Console.WriteLine("Occurrence = " + a[i] + " times");
}
}
}
ผลลัพธ์
Character e Occurrence = 2 times Character i Occurrence = 2 times Character l Occurrence = 2 times