Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse an integer from a string with trailing garbage

Tags:

c#

.net

parsing

I need to parse a decimal integer that appears at the start of a string.

There may be trailing garbage following the decimal number. This needs to be ignored (even if it contains other numbers.)

e.g.

"1" => 1
" 42 " => 42
" 3 -.X.-" => 3
" 2 3 4 5" => 2

Is there a built-in method in the .NET framework to do this?

int.TryParse() is not suitable. It allows trailing spaces but not other trailing characters.

It would be quite easy to implement this but I would prefer to use the standard method if it exists.

like image 744
finnw Avatar asked Oct 13 '09 16:10

finnw


1 Answers

You can use Linq to do this, no Regular Expressions needed:

public static int GetLeadingInt(string input)
{
   return Int32.Parse(new string(input.Trim().TakeWhile(c => char.IsDigit(c) || c == '.').ToArray()));
}

This works for all your provided examples:

string[] tests = new string[] {
   "1",
   " 42 ",
   " 3 -.X.-",
   " 2 3 4 5"
};

foreach (string test in tests)
{
   Console.WriteLine("Result: " + GetLeadingInt(test));
}
like image 124
Donut Avatar answered Sep 24 '22 03:09

Donut