C#: Count a specified character (both cases) in a given string
Count Specific Character in String
Write a C# Sharp program to count a specified character (both cases) in a given string.
Sample Solution:
C# Sharp Code:
using System;
namespace exercises
{
class Program
{
// Main method where the program execution begins
static void Main(string[] args)
{
// Calls the test function with different string arguments and characters, and prints the results
Console.WriteLine(test("PHP Exercises", 'E', 'e')); // Output: 2
Console.WriteLine(test("Latest News, Breaking News LIVE", 'A', 'a')); // Output: 3
}
// Function to count occurrences of characters in a string (case-insensitive)
public static int test(string str1, char uc, char lc)
{
// Using Split method to count occurrences of characters (case-insensitive)
// Splitting the string using provided uppercase and lowercase characters as separators,
// then getting the count of splits minus 1 (as the count of splits equals occurrences)
return str1.Split(uc, lc).Length - 1;
}
}
}
Sample Output:
3 2
Flowchart:
Sample Solution-1:
C# Sharp Code:
using System;
using System.Linq;
namespace exercises
{
class Program
{
// Main method where the program execution begins
static void Main(string[] args)
{
// Calls the test function with different string arguments and characters, and prints the results
Console.WriteLine(test("PHP Exercises", 'E', 'e')); // Output: 2
Console.WriteLine(test("Latest News, Breaking News LIVE", 'A', 'a')); // Output: 3
}
// Function to count occurrences of specified characters in a string (case-insensitive)
public static int test(string str1, char uc, char lc)
{
// Using LINQ's Where method to filter characters that match the specified uppercase or lowercase characters,
// then using Count method to count the occurrences of matching characters
return str1.Where(ch => (ch == lc || ch == uc)).Count();
}
}
}
Sample Output:
3 2
Flowchart:
C# Sharp Code Editor:
Previous: Write a C# Sharp program to create a coded string from a given string, using specified formula.
Next: Write a C# Sharp program to check if a given string contains only lowercase or uppercase characters.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics