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.

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.