Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alphanumeric to numeric only

Tags:

c#

.net

Looking for fast/efficient ways to convert an alphanumeric to a number only string

e.g. +123-456/7890 becomes 1234567890 etc.

the existing code is

foreach(char c in str.ToCharArray() )
  if ( char.IsDigit(c) ) stringBuilder.Append(c);

return stringBuilder.ToString();
like image 614
Kumar Avatar asked Apr 30 '12 06:04

Kumar


People also ask

Can alphanumeric have only numbers?

In computing, the standard alphanumeric codes, such as ASCII, may contain not only ordinary letters and numerals but also punctuation marks and math symbols.

What is alpha numeric only?

Alphanumeric, also referred to as alphameric, is a term that encompasses all of the letters and numerals in a given language set. In layouts designed for English language users, alphanumeric characters are those comprised of the combined set of the 26 alphabetic characters, A to Z, and the 10 Arabic numerals, 0 to 9.

How do you replace non-alphanumeric characters?

To remove all non-alphanumeric characters from a string, call the replace() method, passing it a regular expression that matches all non-alphanumeric characters as the first parameter and an empty string as the second. The replace method returns a new string with all matches replaced. Copied!


2 Answers

LINQ Solution:

return new string(str.Where(char.IsDigit).ToArray());

Not sure if it's more efficient; at-least it's not regex!

like image 92
Andy Avatar answered Oct 15 '22 21:10

Andy


string str="+123-456/7890";
long onlyNumbers= Convert.ToInt64(Regex.Replace(str, @"\D", ""));
like image 26
Chuck Norris Avatar answered Oct 15 '22 20:10

Chuck Norris