We are providing online training of realtime Live project on Asp.Net MVC with Angular and Web API. For more information click here. If you have any query then drop the messase in CONTACT FORM

Wednesday, February 19, 2025

To find and print the digram (a pair of consecutive characters) that appears the most in a given string using C#.

Print the digram which appears maximum number of times in a string
A digram is a sequence of 2 consecutive characters
I/o - "asddaaasadedadaddasasasasas"
O/P - "as"


using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        string input = "asddaaasadedadaddasasasasas";

        Dictionary<string, int> digramCount = new Dictionary<string, int>();

        // Count all digrams in the string
        for (int i = 0; i < input.Length - 1; i++)
        {
            string digram = input.Substring(i, 2);

            if (digramCount.ContainsKey(digram))
                digramCount[digram]++;
            else
                digramCount[digram] = 1;
        }

        // Find the digram with maximum occurrences
        var maxDigram = digramCount.OrderByDescending(x => x.Value).First();

        Console.WriteLine($"\"{maxDigram.Key}\" appears {maxDigram.Value} times");
    }
}

No comments: