Kumar
Kumar

Reputation: 11329

Alphanumeric to numeric only

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();

Upvotes: 9

Views: 4383

Answers (5)

Andy
Andy

Reputation: 1080

LINQ Solution:

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

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

Upvotes: 5

COLD TOLD
COLD TOLD

Reputation: 13579

Here is an another solution found

string justNumbers = new String(text.Where(Char.IsDigit).ToArray());
int numbers = Convert.ToInt32(justNumbers); 

Upvotes: 2

Marshal
Marshal

Reputation: 6651

After seeing many answers which try not to use Regex in this situation, I would like to say actually Regex works much faster in this particular case. I tried calculating time taken for execution using this code snippet

Method suggested by

Edit: These give two completely opposite outputs, i don't know if we should completely trust Ideone than Visual Studio IDE.

Upvotes: 1

Imran Rizvi
Imran Rizvi

Reputation: 7438

Yes RegEx is faster among others , you can make the comparison even more faster using RegexOptions.Compiled to match the negative/positive cases and reside them apart (if such strings can exists)

e.g.

Regex numberOnlyRegEx = new Regex(@"[^0-9]+", RegexOptions.Compiled);

if (!numberOnlyRegEx.IsMatch(str))
  return 0; //default value;

return Convert.ToInt32(numberOnlyRegEx .Replace(str, "[^0-9]+", ""));

Upvotes: 2

Chuck Norris
Chuck Norris

Reputation: 15190

string str="+123-456/7890";
long onlyNumbers= Convert.ToInt64(Regex.Replace(str, @"\D", ""));

Upvotes: 4

Related Questions