To find duplicate characters in a string in C#,

Program:

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        string input = "programming";
        FindDuplicateCharacters(input);
    }

    static void FindDuplicateCharacters(string input)
    {
        Dictionary<char, int> charCount = new Dictionary<char, int>();

        // Iterate through each character in the string
        foreach (char c in input)
        {
            if (charCount.ContainsKey(c))
                charCount[c]++;
            else
                charCount[c] = 1;
        }

        // Display duplicates
        Console.WriteLine("Duplicate characters are:");
        foreach (var item in charCount)
        {
            if (item.Value > 1)
            {
                Console.WriteLine($"Character: {item.Key}, Count: {item.Value}");
            }
        }
    }
}


____________________________________________
Output:
Duplicate characters are:
Character: r, Count: 2
Character: g, Count: 2
Character: m, Count: 2
____________________________________________
Explanation:

1)The Dictionary<char, int> is used to store the count of each character.

2)As you iterate over the string, you check if the character is already in the dictionary. If it is, you increment the count. If not, you add the character to the dictionary with a count of 1.

3)Finally, you loop through the dictionary and print out any characters that have a count greater than 1, indicating they are duplicates.



Comments

Popular posts from this blog

API development using .NET Core - ProductManagmentCRUD

Singleton Design Pattern Realtime Example of banking

Consume API in MVC Application