【问题标题】:C# - Check if entered string is a Integer or notC# - 检查输入的字符串是否为整数
【发布时间】:2018-11-18 16:38:16
【问题描述】:

我想检查输入的字符串是否是整数,例如

12 = 真

+12 = 真

-5 = 真

4.4 = 错误
4as = 假

我使用int.TryParse 制作它,但我想要的是使用 ASCII 而不使用 int.TryParse

string str;
int strint;
int strintoA;
bool flag = false;

while (flag == false)
{
    Console.Write("Enter a Number : ");
    str = Console.ReadLine();
    flag = int.TryParse(str, out strint);              
    if (flag == false)
    {
        Console.WriteLine("Please Enter Numbers Only.");
    }
    else
    {
        strintoA = strint;
        Console.WriteLine("Entered String: " + str + " is a Number!" );
        break;
    }
}
Console.ReadKey();

【问题讨论】:

  • int.TryParse 方法有什么问题?
  • 如果您出于某种原因绝对不能使用 tryparse,您可以使用正则表达式,如此答案:stackoverflow.com/questions/9043551/regex-match-integer-only
  • 不说你为什么不想使用Int32.TryParse 会使这个问题过于宽泛。 (顺便说一句——StringChar 使用 UTF-16,而不是 ASCII。)
  • 如果提供的任何答案有帮助,礼仪是将其标记为“答案”,并可能对其有用性表示赞同。这可以防止这个问题出现在 SOF 中的“显示未回答的问题”下,并且还可以给帮助你的人更多的声誉。

标签: c# console-application


【解决方案1】:

你也可以使用正则表达式:

var regex = new Regex(@"^[-+]?\d+$");
var str = Console.ReadLine();
if (regex.IsMatch(str))
{
    Console.WriteLine($"{str} is a number!");
}

【讨论】:

    【解决方案2】:

    检查第一个字符是否为 -|+|digit,检查其余字符是否为数字

    for (int i = 0; i < str.Length; i++)
    {
        var c = str[i];
        if (i == 0)
        {
            if (!(c == '+' || c == '-' || char.IsDigit(c)) {
                return false;
            }
        }
    
        if (!char.IsDigit(c)) return false;
    }
    return true;
    

    【讨论】:

      【解决方案3】:

      为什么不使用:

      if(intString[0] == '+' || intString[0] == '-') intString = intString.Substring(1, intString.Length - 1);
      bool isNumber = intString.All(char.IsDigit);
      

      【讨论】:

      • 如果 intString 的长度为 0 则失败,然后您会收到 IndexOutOfRangeException
      • 您应该检查所有输入的验证
      【解决方案4】:

      不知道你为什么不想使用int.TryParse,但下面的代码应该可以:

      static bool IsValidInteger(string s)
      {
          var leadingSignSeen = false;
          var digitSeen = false;
          var toParse = s.Trim();
      
          foreach (var c in toParse)
          {
              if (c ==  ' ')
              {
                  if (digitSeen)
                      return false;
              }
              else if (c == '+' || c == '-')
              {
                  if (leadingSignSeen || digitSeen)
                      return false;
      
                  leadingSignSeen = true;
              }
              else if (!char.IsDigit(c))
                  return false;
              else
              {
                  digitSeen = true;
              }
          }
      
          return true;
      }
      

      这将接受任何带有前导符号以及前导和尾随空格的整数。前导符号和数字之间的空格也可以接受。

      【讨论】:

        【解决方案5】:

        仅供参考:您可以重构代码以简化它以获得完全相同的功能输出:

        void Main()
        {
            int result;
            Console.Write("Enter a Number : ");
            while (!int.TryParse(Console.ReadLine(), out result))
            {
                Console.WriteLine("Please Enter Numbers Only.");
                Console.Write("Enter a Number : ");
            }
            Console.WriteLine($"Entered String: {result} is a Number!");
            Console.ReadKey();
        }
        

        如果您有充分的理由不使用 int.TryParse(例如,它缺少某些功能,或者这是一个要求您自己编写的练习),您可以使用上述替换 int.TryParse 来调用到IsNumericCustom,假设以下签名(或将int 类型更改为您需要处理的任何数据类型)。

        public bool IsNumericCustom(string input, out int output)
        {
            //...
        }
        

        或者如果你只关心值是否是数字而不是解析值:

        void Main()
        {
            string result;
            Console.Write("Enter a Number : ");
            //while (!int.TryParse((result = Console.ReadLine()), out _))
            while (!IsNumericCustom((result = Console.ReadLine()))
            {
                Console.WriteLine("Please Enter Numbers Only.");
                Console.Write("Enter a Number : ");
            }
            Console.WriteLine($"Entered String: {result} is a Number!");
            Console.ReadKey();
        }
        
        public bool IsNumericCustom(string input)
        {
            //...
        }
        

        至于IsNumericCustom 中的逻辑,这实际上取决于您希望实现什么/为什么int.TryParse / decimal.TryParse 等不合适。这里有几个实现(使用不同的函数名)。

        using System.Text.RegularExpressions; //https://docs.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex?view=netframework-4.7.2
        //...
        readonly Regex isNumeric = new Regex("^[+-]?\d*\.?\d*$", RegexOptions.Compiled); //treat "." as "0.0", ".9" as "0.9", etc
        readonly Regex isInteger = new Regex("^[+-]?\d+$", RegexOptions.Compiled); //requires at least 1 digit; i.e. "" is not "0" 
        readonly Regex isIntegerLike = new Regex("^[+-]?\d*\.?\0*$", RegexOptions.Compiled); //same as integer, only 12.0 is treated as 12, whilst 12.1 is invalid; i.e. only an integer if we can remove digits after the decimal point without truncating the value.
        
        //...
        public bool IsNumeric(string input)
        {
            return isNumeric.IsMatch(input); //if you'd wanted 4.4 to be true, use this
        }
        public bool IsInteger(string input)
        {
            return isInteger.IsMatch(input); //as you want 4.4 to be false, use this
        }
        public bool IsIntegerLike(string input)
        {
            return isIntegerLike.IsMatch(input); //4.4 is false, but both 4 and 4.0 are true 
        }
        

        【讨论】:

          【解决方案6】:

          根据您的要求,您似乎希望使用 ASCII 代码来断言输入的字符串是否为数字。

          这是我想出的代码:

           string str;
              var index = 1;
              int strintoA = 0;
              bool isNegative = false;
          
              //ASCII list of numbers and signs
              List<int> allowedValues = new List<int> { 43, 45, 48, 49, 50, 51, 52, 53, 54, 55, 56, 
              57 };
              bool flag = false;
          
              while (!flag)
              {
                  Console.WriteLine("Enter a Number : ");
          
                  str = Console.ReadLine();
          
                  if (str.Count(item => allowedValues.Contains((int)item)) == str.Count())
                  {
                      foreach (var item in str.Reverse())
                      {               
                          if (item != 43 && item != 45)
                          {
                              strintoA += index * (item - 48);
                              index = index * 10;
                          }
                          else if(item == 45)
                          {
                              isNegative = true;
                          }
                      }
                      if(isNegative)
                      {
                          strintoA *= -1;
                      }
          
                      Console.WriteLine("Entered String: " + str + " is a Number!");
                      flag = true;
                  }
                  else
                  {
                      Console.WriteLine("Please Enter Numbers Only.");
                  }
              }
              Console.ReadKey();
          }
          

          allowedValues 列表包含数值的 ASCII 表示形式和允许的符号(+ 和 -)。 foreach 循环将重新生成插入的 int 值。

          希望对你有帮助。

          【讨论】:

          • 为了更好的可读性,我建议您使用实际表示('+','1',...)而不是整数
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-03-15
          • 1970-01-01
          • 2011-07-22
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多