C#程式查詢頻率最高的元素


假設字串如下 −

String s = "HeathLedger!";

現在建立一個新陣列。

int []cal = new int[maxCHARS];

建立一個新方法,並將字串和新陣列傳遞到其中。找出字元的最大出現次數。

static void calculate(String s, int[] cal) {
   for (int i = 0; i < s.Length; i++)
   cal[s[i]]++;
}

讓我們看一下完整程式碼 −

示例

 線上演示

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 = "thisisit!";
      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 i
Occurrence = 3 times
Character s
Occurrence = 2 times
Character t
Occurrence = 2 times

更新日期: 2020 年 6 月 22 日

884 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.