Find and extract a number from a string

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

    Here is another Linq approach which extracts the first number out of a string.

    string input = "123 foo 456";
    int result = 0;
    bool success = int.TryParse(new string(input
                         .SkipWhile(x => !char.IsDigit(x))
                         .TakeWhile(x => char.IsDigit(x))
                         .ToArray()), out result);
    

    Examples:

    string input = "123 foo 456"; // 123
    string input = "foo 456";     // 456
    string input = "123 foo";     // 123
    

提交回复
热议问题