Tech Point Fundamentals

Thursday, December 2, 2021

C# Program to Find the Occurrence of Each Character in a String

C# Program to Find the Occurrence of Each Character in a String

coding-interview-question-csharp

Most of the IT companies check the coding skills and problem-solving skills as well along with the theoretical interview questions. Sometimes you are free to write the pseudo code and sometimes you are asked to write the complete program either on any paper or any editor. 


This question is asked in the coding interview to write the program. Here you can find the program as well as a live running program so that you can test the program immediately.


Watch our videos here





Question: 


How can you find the maximum occurrence of each character in a given string? Write a program to find the count of each character in a given string.





C# Program To Find the Occurrence of Each Character


       
 

// Author 	: Tech Point Fundamentals
// Website 	: www.techpointfunda.com
// Channel	: https://www.youtube.com/c/TechPointFundamentals
// Demo		: Occurrence of Each Character

using System;
using System.Collections.Generic;

public class Program
{
 public static void Main()
 {
   string inputString = "Tech Point Fundamentals";		
   
   Console.WriteLine("Input String : " + inputString);
   Console.WriteLine("Character Counts : ");
   CharactersCount(inputString);
 }
 
 public static void CharactersCount(string inputString)    
 {               
  var charCountResult = CharCountDictionary(inputString);              
  
  foreach (var count in charCountResult)    
  {    
  	Console.WriteLine(" {0} - {1} ", count.Key, count.Value);    
  }    
 }    
 
 public static SortedDictionary<char, int> CharCountDictionary(string input)    
 {    
  SortedDictionary<char, int> countDict = new SortedDictionary<char, int>();    
 
   foreach (char item in input)    
   {
   	
   	if (!(countDict.ContainsKey(item)) )    
   	{    
   		countDict.Add(item, 1);    
   	}    
   	else    
   	{    
   		countDict[item]++;    
   	}    
   }
   return countDict;    
 } 
}





Output: 

                Input String : Tech Point Fundamentals
Character Counts (Case Sensitive) : 
   - 2 
F - 1 
P - 1 
T - 1 
a - 2 
c - 1 
d - 1 
e - 2 
h - 1 
i - 1 
l - 1 
m - 1 
n - 3 
o - 1 
s - 1 
t - 2 
u - 1




Live Demo






No comments:

Post a Comment

Please do not enter any HTML. JavaScript or spam link in the comment box.