Find and extract a number from a string

前端 未结 29 3193
温柔的废话
温柔的废话 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:54

    Extension method to get all positive numbers contained in a string:

        public static List Numbers(this string str)
        {
            var nums = new List();
            var start = -1;
            for (int i = 0; i < str.Length; i++)
            {
                if (start < 0 && Char.IsDigit(str[i]))
                {
                    start = i;
                }
                else if (start >= 0 && !Char.IsDigit(str[i]))
                {
                    nums.Add(long.Parse(str.Substring(start, i - start)));
                    start = -1;
                }
            }
            if (start >= 0)
                nums.Add(long.Parse(str.Substring(start, str.Length - start)));
            return nums;
        }
    

    If you want negative numbers as well simply modify this code to handle the minus sign (-)

    Given this input:

    "I was born in 1989, 27 years ago from now (2016)"
    

    The resulting numbers list will be:

    [1989, 27, 2016]
    

提交回复
热议问题