Introduction

In this blog, we create a C# program that takes a string as an input, and then we give output as how many characters are in that string, how many characters are letters, how many characters are digits and how many characters are is a special character like symbol, space, etc.
Code
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace CountTotalNumberInString
  7. {
  8. class Program
  9. {
  10. static void Main(string[] args)
  11. {
  12. Console.WriteLine("--------------------------------------------------------");
  13. Console.WriteLine("Program to count of letter, digit and special characters ");
  14. Console.WriteLine("--------------------------------------------------------");
  15. Console.Write("Enter a string :");
  16. string str = Console.ReadLine();
  17. int totalCharacter = 0, totalLetterChar = 0, totalDigitChar = 0, totalSpecialChar = 0;
  18. char[] strArray = str.ToCharArray();
  19. foreach (var item in strArray)
  20. {
  21. if (char.IsDigit(item))
  22. totalDigitChar++;
  23. if (char.IsLetter(item))
  24. totalLetterChar++;
  25. if (!char.IsLetterOrDigit(item))
  26. totalSpecialChar++;
  27. totalCharacter++;
  28. }
  29. Console.WriteLine("--------------------------------------------------------");
  30. Console.WriteLine("Entered String : "+str);
  31. Console.WriteLine("--------------------------------------------------------");
  32. Console.WriteLine("Total Characters In String : "+totalCharacter);
  33. Console.WriteLine("Total Letter Character String : "+totalLetterChar);
  34. Console.WriteLine("Total Digit Character String : "+totalDigitChar);
  35. Console.WriteLine("Total Specia Character String : "+totalSpecialChar);
  36. Console.WriteLine("--------------------------------------------------------");
  37. Console.ReadKey();
  38. }
  39. }
  40. }
Output
Count Total Letters, Digits And Special Characters From String
Explanation