代码之家  ›  专栏  ›  技术社区  ›  CoderDennis

仅转换字符串整数部分的最佳方法

  •  2
  • CoderDennis  · 技术社区  · 14 年前

    我在找这样的东西:

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

    我想我可以使用RegEx从字符串的开头提取数字,但是在我自己滚动之前,我想看看这样的东西是否已经存在。好像我曾经用过一种语言,它有这种类型的转换函数,但我在.NET中找不到它。

    2 回复  |  直到 14 年前
        1
  •  1
  •   Victor Hurdugaci    14 年前

    正如Raj提到的,使用regex。

    伪代码:

    r = Regex("[0-9]+") //Or more complex if you want other numbers
    foreach m in r.Matches(InputString)
        number = int.Parse(m)
    
        2
  •  1
  •   Raj    14 年前

    在你陈述的时候使用正则表达式似乎是一个不错的选择。