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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP