views:

38

answers:

2

In .NET the Integer Parse methods are useful for converting a string to an int, but the string must be a valid integer without any extra characters. Is there a function that will convert the integer portion of a string to an int and ignore everything else in the input string?

I'm looking for something like this:

int x = ConvertFunction("1A"); // x should equal 1 instead of throwing an error

I guess I could use RegEx to extract the digits from the beginning of the string, but before I roll my own, I wanted to see if something like this already existed. It seems like I've used a language at one time or another that had this type of conversion function, but I can't find it in .NET.

+1  A: 

Using a RegEx as you state seems to be the way to go.

Raj
+1  A: 

As Raj mentioned use regex.

Pseudocode:

r = Regex("[0-9]+") //Or more complex if you want other numbers
foreach m in r.Matches(InputString)
    number = int.Parse(m)
Victor Hurdugaci