Stripping out non-numeric characters in string

后端 未结 11 586
南旧
南旧 2021-01-30 09:46

Hey Im looking to strip out non-numeric characters in a string in ASP.NET C#

So i.e 40,595 p.a.

would end up with 40595

Thanks

11条回答
  •  遥遥无期
    2021-01-30 10:23

    Use either a regular expression that's only capturing 0-9 and throws away the rest. A regular expression is an operation that's going to cost a lot the first time though. Or do something like this:

    var sb = new StringBuilder();
    var goodChars = "0123456789".ToCharArray();
    var input = "40,595";
    foreach(var c in input)
    {
      if(goodChars.IndexOf(c) >= 0)
        sb.Append(c);
    }
    var output = sb.ToString();
    

    Something like that I think, I haven't compiled though..

    LINQ is, as Fredrik said, also an option

提交回复
热议问题