Find and extract a number from a string

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

    go through the string and use Char.IsDigit

    string a = "str123";
    string b = string.Empty;
    int val;
    
    for (int i=0; i< a.Length; i++)
    {
        if (Char.IsDigit(a[i]))
            b += a[i];
    }
    
    if (b.Length>0)
        val = int.Parse(b);
    

提交回复
热议问题