Tech Point Fundamentals

Thursday, December 9, 2021

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

C# Program to Find the No of Occurrence of a 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 total number of occurrences of a given character in a string? Write a program to find the same.



C# Program To Find the Frequency of a Character in a String


       
 

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

using System;

public class Program
{
 public static void Main()
 {
   string inputString = "Tech Point Fundamentals";		
   char inputCharacter = 't';		
   
   Console.WriteLine("Input String : " + inputString);
   Console.WriteLine("Input Character : " + inputCharacter);		
   Console.WriteLine("Character Max Count - Way 1 : " + CharacterCount(inputString, inputCharacter));	
   Console.WriteLine("Character Max Count - Way 2 : " + CharacterCount_Way2(inputString, inputCharacter));
 }	  	
	
public static int CharacterCount(string inputString, char character)    
{  		
  int count = 0;		
  
  char[] charArray = inputString.ToLower().ToCharArray(); 				
  
  foreach (char item in charArray)
  {
  	if (item == character)
  	{
  		count = count + 1;
  	}
  }

 return count;
}	
	
public static int CharacterCount_Way2(string inputString, char character)    
{  		
  int count = 0;
  inputString = inputString.ToLower();
  
  for (int index = 0; index < inputString.Length; index++)
  {
  	if (inputString[index] == character)
  	{
  		count = count + 1;
  	}
  }
  
  return count;
}	
}





Output: 

Input String : Tech Point Fundamentals
Input Character : t
Character Max Count - Way 1 : 3
Character Max Count - Way 2 : 3




Live Demo






No comments:

Post a Comment

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