开发者

Best method for converting only the integer portion of a string

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 some开发者_StackOverflow中文版thing 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.


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)


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜