Find and extract a number from a string

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

    Here is my Algorithm

        //Fast, C Language friendly
        public static int GetNumber(string Text)
        {
            int val = 0;
            for(int i = 0; i < Text.Length; i++)
            {
                char c = Text[i];
                if (c >= '0' && c <= '9')
                {
                    val *= 10;
                    //(ASCII code reference)
                    val += c - 48;
                }
            }
            return val;
        }
    

提交回复
热议问题