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
how to check if the character is an integer
提问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
Integer.TryParseworks well.
Integer.TryParse效果很好。
回答by lhan
Use System.Char.IsDigitmethod
回答by Aamir
回答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:
回答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))

