อักขระที่เกิดขึ้นสูงสุดในสตริงคืออักขระที่เกิดขึ้นเป็นจำนวนมากที่สุด ซึ่งสามารถแสดงให้เห็นได้โดยใช้ตัวอย่างต่อไปนี้
String: apples are red The highest occurring character in the above string is e as it occurs 3 times, which is more than the occurrence of any other character.
โปรแกรมที่ได้รับอักขระที่เกิดขึ้นสูงสุดในสตริงโดยใช้ C# จะได้รับดังนี้
ตัวอย่าง
using System;
namespace charCountDemo {
public class Example {
public static void Main() {
String str = "abracadabra";
int []charCount = new int[256];
int length = str.Length;
for (int i = 0; i < length; i++) {
charCount[str[i]]++;
}
int maxCount = -1;
char character = ' ';
for (int i = 0; i < length; i++) {
if (maxCount < charCount[str[i]]) {
maxCount = charCount[str[i]];
character = str[i];
}
}
Console.WriteLine("The string is: " + str);
Console.WriteLine("The highest occurring character in the above string is: " + character);
Console.WriteLine("Number of times this character occurs: " + maxCount);
}
}
} ผลลัพธ์
ผลลัพธ์ของโปรแกรมข้างต้นมีดังนี้
The string is: abracadabra The highest occurring character in the above string is: a Number of times this character occurs: 5
ตอนนี้ เรามาทำความเข้าใจโปรแกรมข้างต้นกัน
สตริง str คือ abracadabra อาร์เรย์ใหม่ charCount ถูกสร้างขึ้นซึ่งมีขนาด 256 และแสดงอักขระทั้งหมดในตาราง ASCII จากนั้นสตริง str จะถูกข้ามโดยใช้ for loop และค่าใน charCount จะเพิ่มขึ้นตามอักขระในสตริง ซึ่งสามารถเห็นได้ในข้อมูลโค้ดต่อไปนี้
String str = "abracadabra";
int []charCount = new int[256];
int length = str.Length;
for (int i = 0; i < length; i++) {
charCount[str[i]]++;
} จำนวนเต็ม maxCount เก็บจำนวนสูงสุดและอักขระเป็นค่าถ่านที่เกิดขึ้นครั้งสูงสุด ค่าของ maxCount และอักขระสามารถกำหนดได้โดยใช้ for loop ซึ่งสามารถเห็นได้ในข้อมูลโค้ดต่อไปนี้
int maxCount = -1;
char character = ' ';
for (int i = 0; i < length; i++) {
if (maxCount < charCount[str[i]]) {
maxCount = charCount[str[i]];
character = str[i];
}
} สุดท้าย ค่าของ str, maxCount และอักขระจะปรากฏขึ้น ซึ่งสามารถเห็นได้ในข้อมูลโค้ดต่อไปนี้
Console.WriteLine("The string is: " + str);
Console.WriteLine("The highest occurring character in the above string is: " + character);
Console.WriteLine("Number of times this character occurs: " + maxCount);