如何使用C#獲取字串中出現頻率最高的字元?


字串中出現頻率最高的字元是指出現次數最多的字元。可以使用以下示例進行演示。

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表中的所有字元。然後使用for迴圈遍歷字串str,並根據字串中的字元遞增charCount中的值。這可以在下面的程式碼片段中看到。

String str = "abracadabra";
int []charCount = new int[256];
int length = str.Length;
for (int i = 0; i < length; i++) {
   charCount[str[i]]++;
}

整數maxCount儲存最大計數,character是出現次數最多的字元值。可以使用for迴圈確定maxCount和character的值。這可以在下面的程式碼片段中看到。

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和character的值。這可以在下面的程式碼片段中看到。

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);

更新於:2020年6月26日

4K+ 次瀏覽

啟動你的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.