Find and extract a number from a string

前端 未结 29 2734
温柔的废话
温柔的废话 2020-11-22 03:19

I have a requirement to find and extract a number contained within a string.

For example, from these strings:

string test = \"1 test\"
string test1 =         


        
29条回答
  •  伪装坚强ぢ
    2020-11-22 03:53

    The question doesn't explicitly state that you just want the characters 0 to 9 but it wouldn't be a stretch to believe that is true from your example set and comments. So here is the code that does that.

            string digitsOnly = String.Empty;
            foreach (char c in s)
            {
                // Do not use IsDigit as it will include more than the characters 0 through to 9
                if (c >= '0' && c <= '9') digitsOnly += c;
            }
    

    Why you don't want to use Char.IsDigit() - Numbers include characters such as fractions, subscripts, superscripts, Roman numerals, currency numerators, encircled numbers, and script-specific digits.

提交回复
热议问题