In this article, we will find the count of a particular character in a given string using c#
class Program
{
static void Main(string[] args)
{
#region Find a given character count in a string
Console.WriteLine("Enter a String :");
string str = Console.ReadLine();
Console.WriteLine("Enter the character:");
char ch = Console.ReadLine();
Console.WriteLine("The character " + ch + " occurs " + GetCharacterCount(str, ch) + " times in the given string");
Console.ReadKey();
#endregion
}
#region Find a given character count in a string
private static int GetCharacterCount(string str, char ch)
{
int count = 0;
int i = 0;
// Search starts in the string from index (where the given character first occurs in the string at // start index 0) and loops through entire string till the index not equals to -1
while ((i = str.IndexOf(ch, i)) != -1)
{
i += ch.ToString().Length; // keep increasing the loop count
count++;
}
return count;
}
#endregion
class Program
{
static void Main(string[] args)
{
#region Find a given character count in a string
Console.WriteLine("Enter a String :");
string str = Console.ReadLine();
Console.WriteLine("Enter the character:");
char ch = Console.ReadLine();
Console.WriteLine("The character " + ch + " occurs " + GetCharacterCount(str, ch) + " times in the given string");
Console.ReadKey();
#endregion
}
#region Find a given character count in a string
private static int GetCharacterCount(string str, char ch)
{
int count = 0;
int i = 0;
// Search starts in the string from index (where the given character first occurs in the string at // start index 0) and loops through entire string till the index not equals to -1
while ((i = str.IndexOf(ch, i)) != -1)
{
i += ch.ToString().Length; // keep increasing the loop count
count++;
}
return count;
}
#endregion
}
Console Output:
Enter a String :
AMRENDRA BAHUBALI
Enter the character:
A
The character A occurs 4 times in the given string
No comments:
Post a Comment