C# 如何检查字符是否为整数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12866214/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 00:44:37  来源:igfitidea点击:

how to check if the character is an integer

c#

提问by darking050

I am looking for a function that can check the character if it is a integer and do something is so.

我正在寻找一个函数,它可以检查字符是否为整数,并执行某些操作。

char a = '1';

if (Function(a))
{
  do something
}

回答by lhan

回答by lhan

回答by Aamir

Try Char.IsNumber. Documentation and examples can be found here

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

回答by Rahul Tripathi

Try using System.Char.IsDigitmethod.

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

回答by Corith Malin

It may be better to just use a switch statement. Something like:

最好只使用 switch 语句。就像是:

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

This will work as long as you're only looking for characters 0-9. Anything more than that (say "10") would be a string and not a character. If you're trying to just see if some input is an integer and the input is a string, you can do:

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

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

回答by D Stanley

If you want just the pure 0-9digits, use

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

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

IsNumericand IsDigitboth return true for some characters outside the 0-9 range:

IsNumeric并且IsDigit对于 0-9 范围之外的某些字符都返回 true:

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

C#中Char.IsDigit()和Char.IsNumber()的区别

回答by A.Clymer

The bool Char.IsDigit(char c);Method should work perfectly for this instance.

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

char a = '1';

if (Char.IsDigit(a))
{
  //do something
}

回答by Lê V? Huy

Simplest answer:

最简单的答案:

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

回答by FredyWenger

I have to check the first to characters of a string and if the third character is numericand do it with MyString.All(char.IsDigit):

我必须检查字符串的第一个字符,如果第三个字符是数字,并使用MyString.All(char.IsDigit) 进行检查

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