How to Extract Digits From a String in C#

How to Extract digits from a string in Csharp. String is a common data type which we use in our code but some time we have to perform some kind of function on string. It is a example of how you can extract numeric digits. Follow the following steps:
Requirement for the use of timer control is following.

- Operating System : Windows XP, Windows 7 , Vista
- Platform : .Net 2.0 or greater
- IDE : Visual Studio
- Language : Csharp

Now Follow the following steps :

- Create New Project on Visual Studio
- Select language C#
- Now Select the Console Application

Add this to your code at top :

-

using System.Text.RegularExpressions;

Use the Following Function :

public static string[] ExtractDigits(string data)
{
System.Text.RegularExpressions.MatchCollection matches
= System.Text.RegularExpressions.Regex.Matches(data,@"(\d+\.?\d*|\.\d+)");
string[] MatchList = new string[matches.Count];
int c = 0;
foreach (System.Text.RegularExpressions.Match match in matches)
{
MatchList[c] = match.ToString();
c++;
}
return MatchList;
}
Now you can use this function in many forms for example im using it for sum of digits :

static void Main(string[] args)
{
string st = "sfdsdfj3w4ew3434mnskjfns34wq34";
int sum = 0;
string[] arra = ExtractDigits(st);

for (int i = 0; i < arra.Length; i++) { Console.WriteLine(arra[i]); sum+= Convert.ToInt32(arra[i]); } Console.WriteLine("SUM is : "+sum.ToString()); Console.ReadLine(); }

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Powered by Blogger