C# tutorial-count number of digits in a string


Char structure

Counting digits in a string

The Char structure provides a method called IsDigit(char c) to see whether a character in a string is a digit. This method takes one argument. The argument is the character that you want to check. In the example below, we use IsDigit(char c) method to count the number of digits in a string "ID123223";

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ConsoleApplication1
{
class Program
{

static void Main(string[] args)
{
string st = "ID12323";
int countch = 0,i;
for(i=0;i<st.Length;i++)
if(Char.IsDigit(st[i])) countch++;
Console.WriteLine("Number of digits:{0}", countch);
Console.ReadLine();


}

}
}

If you want to indicate whether a character in a specified position of a string is a digit, you can use IsDigit(string st, int position) method.

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ConsoleApplication1
{
class Program
{

static void Main(string[] args)
{
   string name;
   Console.Write("Enter your name:");
   name = Console.ReadLine();
   if (Char.IsDigit(name, 0)) Console.WriteLine("The name can't be started with a digit.");
   else Console.WriteLine("Welcome {0}", name);

   Console.ReadLine();


     }

  }
}




Comments

CAPTCHA image




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.