如何使用 C# 打印字符串中的重复字符?

王林
王林 转载
2023-08-28 11:53:09 480浏览

如何使用 C# 打印字符串中的重复字符?

设置字符的最大值。

static int maxCHARS = 256;

现在显示字符串中的重复字符。

String s = "Welcometomywebsite!";

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");
}

上面,我们计算了字符的频率。下面的完整示例显示了相同的内容 -

示例

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 = "Welcometomywebsite!";

      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");
      }
   }
}

以上就是如何使用 C# 打印字符串中的重复字符?的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:tutorialspoint,如有侵犯,请联系admin@php.cn删除