【问题标题】:how to check if the character is an integer如何检查字符是否为整数
【发布时间】:2012-10-12 19:58:26
【问题描述】:

我正在寻找一个函数,它可以检查字符是否为整数并做某事。

char a = '1';

if (Function(a))
{
  do something
}

【问题讨论】:

  • 旁注:您应该考虑是否需要“整数”(作为数字序列 - 有这样的几个字符)、“数字”(多种语言中的 0-9)或“数字” (1/2,...)

标签: c#


【解决方案1】:

使用System.Char.IsDigit方法

【讨论】:

  • +1 到 IsDigit 和 IsNumber。请注意,两者都不能保证字符是“整数”,因为 IsDigit 仅表示它位于可能更长整数的数字上,IsNumber 可以是浮点数(即 1/2)。
  • IsDigit 涵盖 0-9 和其他字符集中的等价物,并且对于单个字符始终是整数(对于更长的字符串,请使用 Integer.TryParse)。 IsNumber 为 0-9 以及“数字、其他”和“数字、字母”组中的一些更有趣的 Unicode 字符返回 true,例如 ½(即 1 个字符)fileformat.info/info/unicode/category/No/list.htm
  • IsDigit 将为所有这些字符返回 true;除了 0-9 之外,它们不会通过 int.TryParse 在英语机器上使用默认区域性设置解析为整数 - fileformat.info/info/unicode/category/Nd/list.htm
【解决方案2】:

如果您只想要纯 0-9 数字,请使用

if(a>='0' && a<='9')

IsNumericIsDigit 对于 0-9 范围之外的某些字符都返回 true:

Difference between Char.IsDigit() and Char.IsNumber() in C#

【讨论】:

    【解决方案3】:

    【讨论】:

    • IsNumeric 为非数字字符返回 truestackoverflow.com/questions/228532/…
    • 感谢有关 IsNumber 的提醒,我不知道这一点。我会从我的答案中删除它。你知道 Integer.TryParse 是否对非数字字符做同样的事情吗?
    • 从未尝试过,但对于美国文化,我怀疑它只会考虑0-9
    【解决方案4】:

    bool Char.IsDigit(char c); 方法应该非常适合这个实例。

    char a = '1';
    
    if (Char.IsDigit(a))
    {
      //do something
    }
    

    【讨论】:

      【解决方案5】:

      尝试使用System.Char.IsDigit 方法。

      【讨论】:

        【解决方案6】:

        试试Char.IsNumber。文档和示例可以在here找到。

        【讨论】:

          【解决方案7】:

          最好只使用 switch 语句。比如:

          switch(a)
          {
            case '1':
              //do something.
              break;
            case '2':
              // do something else.
              break;
            default: // Not an integer
              throw new FormatException();
              break;
          }
          

          只要您只查找字符 0-9,这将起作用。除此之外的任何东西(比如“10”)都是字符串而不是字符。如果您只是想查看某个输入是否为整数且输入为字符串,您可以这样做:

          try
          {
            Convert.ToInt32("10")
          }
          catch (FormatException err)
          {
            // Not an integer, display some error.
          }
          

          【讨论】:

            【解决方案8】:

            最简单的答案:

            char chr = '1';
            char.isDigit(chr)
            

            【讨论】:

              【解决方案9】:

              我必须检查字符串的第一个字符,第三个字符是否为数字,然后使用 MyString.All(char.IsDigit): p>

              if (cAdresse.Trim().ToUpper().Substring(0, 2) == "FZ" & cAdresse.Trim().ToUpper().Substring(2, 1).All(char.IsDigit))
              

              【讨论】:

                猜你喜欢
                • 2012-04-27
                • 1970-01-01
                • 2021-10-03
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2016-02-18
                • 2023-03-30
                • 1970-01-01
                相关资源
                最近更新 更多