要获得字符串中出现的最大字符,请循环直到给定字符串的长度并找到出现的字符。
这样,设置一个新的数组来计算-
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