Program to Find the Frequency of Characters in a String - (C# Basic Programs)
Finding the frequency of characters in a string is a common programming exercise that helps improve problem-solving skills. In this tutorial, we will discuss a program to find the frequency of characters in a string using C# programming language.
Syntax
The syntax of the program to find the frequency of characters in a string using C# is as follows:
string str = "sample string";
Dictionary<char, int> charFrequency = new Dictionary<char, int>();
foreach (char c in str)
{
if (charFrequency.ContainsKey(c))
{
charFrequency[c]++;
}
else
{
charFrequency.Add(c, 1);
}
}
foreach (KeyValuePair<char, int> pair in charFrequency)
{
Console.WriteLine("Character: {0} Frequency: {1}", pair.Key, pair.Value);
}
Example
using System;
using System.Collections.Generic;
public class Program
{
public static void Main(string[] args)
{
string str = "hello world";
Dictionary<char, int> charFrequency = new Dictionary<char, int>();
foreach (char c in str)
{
if (charFrequency.ContainsKey(c))
{
charFrequency[c]++;
}
else
{
charFrequency.Add(c, 1);
}
}
foreach (KeyValuePair<char, int> pair in charFrequency)
{
Console.WriteLine("Character: {0} Frequency: {1}", pair.Key, pair.Value);
}
}
}
Output:
Character: h Frequency: 1
Character: e Frequency: 1
Character: l Frequency: 3
Character: o Frequency: 2
Character: Frequency: 1
Character: w Frequency: 1
Character: r Frequency: 1
Character: d Frequency: 1
Explanation
The program takes a string as input and uses a dictionary to count the number of occurrences of each character in the string. The program iterates through each character in the string and checks if the character is already present in the dictionary. If the character is present, the frequency of the character is incremented, otherwise, a new entry is added to the dictionary. Finally, the program displays the characters and their frequencies using a foreach loop to iterate through the dictionary.
Use
Finding the frequency of characters in a string is a useful exercise for programmers to improve their problem-solving skills. This program can be used to write more complex programs that perform tasks such as counting the number of vowels, consonants, or digits in a string.
Summary
In this tutorial, we have discussed a program to find the frequency of characters in a string using C# programming language. We have seen the syntax, examples, explanation, and use of finding the frequency of characters programming in C#. By practicing these exercises, programmers can improve their problem-solving skills and become better equipped to tackle complex coding challenges.