Saturday, 27 March 2021

In this article, we will see How to find Occurrences of a character in a String C#
There are multiple ways to find the Occurrences of a character in a String C# however we need to use best and optimized performance oriented way to achieve this functionality. 

Using Basic Approach/Logic: 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace count_occurence_of_char_using_basic_logic
{
    class Program
    {
        static void Main(string[] args)
        {
            string _str = "occurences";
            Console.WriteLine("String: " + _str);
            while (_str.Length > 0)
            {
                Console.Write(_str[0] + " = ");
                int count = 0;
                for (int j = 0; j < _str.Length; j++)
                {
                    if (_str[0] == _str[j])
                    {
                        count++;
                    }
                }
                Console.WriteLine(count);
                _str = _str.Replace(_str[0].ToString(), string.Empty);
            }
            Console.ReadLine();
        }
    }
}


Using Dictionary:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Count_occurences_of_char_using_dictionary_in_csharp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter the string : ");
            string message = Console.ReadLine();
            Dictionary<char, int> dict = new Dictionary<char, int>();
            foreach (char ch in message.Replace(" ", string.Empty))
            {
                if (dict.ContainsKey(ch))
                {
                    dict[ch] = dict[ch] + 1;
                }
                else
                {
                    dict.Add(ch, 1);
                }
            }
            foreach (var item in dict.Keys)
            {
                Console.WriteLine(item + " : " + dict[item]);
            }
            Console.ReadKey();
        }
    }
}

How to find Occurrences of a character in a String C#

In this article, we will see How to find Occurrences of a character in a String C# ?  There are multiple ways to find the Occurrences of a ...

 

Technical Talks © 2015 - Designed by Templateism.com, Distributed By Blogger Templates