How to check if my string only numeric

后端 未结 7 2048
臣服心动
臣服心动 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:26

    int.TryParse() method will return false for non numeric strings

    0 讨论(0)
  • 2020-12-18 18:32

    If you want to use Regex you would have to use something like this:

    string regExPattern = @"^[0-9]+$";
    System.Text.RegularExpressions.Regex pattern = new System.Text.RegularExpressions.Regex(regExPattern);
    return pattern.IsMatch(yourString);
    
    0 讨论(0)
  • 2020-12-18 18:35

    Your question is not clear. Is . allowed in the string? Is ¼ allowed?

    string source = GetTheString();
    
    //only 0-9 allowed in the string, which almost equals to int.TryParse
    bool allDigits = source.All(char.IsDigit); 
    bool alternative = int.TryParse(source,out result);
    
    //allow other "numbers" like ¼
    bool allNumbers = source.All(char.IsNumber);
    
    0 讨论(0)
  • 2020-12-18 18:37

    You con do like that:

    public bool IsNumeric(string val)
    {
        if(int.TryParse(val)) return true;
        else if(double.TryParse(val)) return true;
        else if(float.TryParse(val)) return true;
        else return false;
    }
    
    0 讨论(0)
  • 2020-12-18 18:44

    You could use Regex or int.TryParse.

    See also C# Equivalent of VB's IsNumeric()

    0 讨论(0)
  • 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);
    
    0 讨论(0)
提交回复
热议问题