How can I check if a string is a number?

后端 未结 25 1767
伪装坚强ぢ
伪装坚强ぢ 2020-11-27 21:04

I\'d like to know on C# how to check if a string is a number (and just a number).

Example :

141241   Yes
232a23   No
12412a   No

an

25条回答
  •  眼角桃花
    2020-11-27 21:27

    If you want to validate if each character is a digit and also return the character that is not a digit as part of the error message validation, then you can loop through each char.

    string num = "123x";
    
    foreach (char c in num.ToArray())
    {
        if (!Char.IsDigit(c))
        {
            Console.WriteLine("character " + c + " is not a number");
            return;
        }
    }
    

提交回复
热议问题