How to print duplicate characters in a String using C#?


Set maximum value for char.

static int maxCHARS = 256;

Now display the duplicate characters in the string.

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

Above, we have calculated the frequency of characters. The same is shown below in the complete example −

Example

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

Updated on: 22-Jun-2020

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements