Home »
.Net »
C# Programs
C# - Count Total Number of Digits in a String
Given a string, we have to count number of digits in an alpha-numeric string using C# program.
Submitted by Nidhi, on October 12, 2020 [Last updated : March 21, 2023]
Here, we will find the count of numbers in a specified string by checking each digit one by one.
C# program to count the total number of digits in an alpha-numeric string
The source code to count the total number of digits in an alphanumeric string is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.
//C# program to count the total number of
//digits in the alpha-numeric string.
using System;
class Demo
{
public static void Main()
{
string str="";
int count=0;
Console.Write("Enter the string: ");
str = Console.ReadLine();
for (int i=0; i<str.Length; i++)
{
if ((str[i] >= '0') && (str[i] <= '9'))
{
count++;
}
}
Console.WriteLine("Number of Digits in the string: "+ count);
}
}
Output
Enter the string: A124B27
Number of Digits in the string: 5
Press any key to continue . . .
Explanation
Here, we created a class Demo that contains the Main() method. The Main() method is the entry point for the program, here we created two local variables str and count. Then we read the value of the string and check each character of the string, if the character is a digit the increase the value of the count variable. That's why we finally got the count of all digits present in the input string.
C# Basic Programs »