C# program to Print duplicate characters in a String
Here's a C# program that prints the duplicate characters in a given string:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
string inputString = "Hello, World!";
PrintDuplicateCharacters(inputString);
}
static void PrintDuplicateCharacters(string inputString)
{
Dictionary charCount = new Dictionary();
// Count the occurrences of each character in the string
foreach (char c in inputString)
{
if (charCount.ContainsKey(c))
{
charCount[c]++;
}
else
{
charCount[c] = 1;
}
}
// Print the duplicate characters
Console.WriteLine("Duplicate characters in the string:");
foreach (KeyValuePair pair in charCount)
{
if (pair.Value > 1)
{
Console.WriteLine("{0}: {1}", pair.Key, pair.Value);
}
}
}
}
In this program, we use a Dictionary called charCount to store the count of each character in the input string. We iterate through each character in the string and update its count in the dictionary. Finally, we iterate over the dictionary and print the characters that have a count greater than 1, indicating duplicates.
The output of the above program would be:
Duplicate characters in the string:
l: 3
o: 2
In this case, the characters 'l' and 'o' appear multiple times in the string "Hello, World!".