How to check if my string only numeric

后端 未结 7 2051
臣服心动
臣服心动 2020-12-18 17:49

How I can check if my string only contain numbers?

I don\'t remember. Something like isnumeric?

7条回答
  •  独厮守ぢ
    2020-12-18 18:50

    Just check each character.

    bool IsAllDigits(string s)
    {
        foreach (char c in s)
        {
            if (!char.IsDigit(c))
                return false;
        }
        return true;
    }
    

    Or use LINQ.

    bool IsAllDigits(string s) => s.All(char.IsDigit);
    

    If you want to know whether or not a value entered into your program represents a valid integer value (in the range of int), you can use TryParse(). Note that this approach is not the same as checking if the string contains only numbers.

    bool IsAllDigits(string s) => int.TryParse(s, out int i);
    

提交回复
热议问题