How to count the letters, spaces, numbers and other characters of a string in C#

1 Answer

0 votes
using System;

class Program
{
     public static void count(String s) {
        int letters = 0, spaces = 0, numbers = 0, otherchars = 0;
          
        for (int i = 0; i < s.Length; i++) {
            if (Char.IsLetter(s[i])) {
                letters++;
            }
            else if (Char.IsDigit(s[i])) {
                numbers++;
            }
            else if (Char.IsWhiteSpace(s[i])) {
                spaces++;
            }
            else {
                otherchars++;
            }
        }
        Console.WriteLine("letters: " + letters);
        Console.WriteLine("spaces: " + spaces);
        Console.WriteLine("numbers: " + numbers);
        Console.WriteLine("others: " + otherchars);
    }
    static void Main() {
        String s = "C# $100%     Prog()ramming   99 !!!";
          
        count(s);
    }
}
  
  
 
  
/*
run:
  
letters: 12
spaces: 10
numbers: 5
others: 8
  
*/

 



answered Aug 7, 2021 by avibootz
...