C# 程式用以獲取字串中最常出現的字元


若要獲取字串中最常出現的字元,可迴圈迭代給定字串的長度並找出該字元的出現次數。

然後,設定一個新陣列來計算 −

for (int i = 0; i < s.Length; i++)
   a[s[i]]++;
}

我們上面使用的值 −

String s = "livelife!";
int[] a = new int[maxCHARS];

現在顯示字元及其出現次數 −

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

更新於: 22-Jun-2020

672 次檢視

開啟你的 職業生涯

完成本課程即可獲得認證

開始學習
廣告