獲取字串中出現次數最多的字元的 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 次瀏覽

開啟您的職業生涯

完成課程,獲得認證

開始
廣告