[英]Check if a char matches any char in a char array
Essentially, I'm trying to check if textbox2.Text
contains anything that isn't an integer. 本质上,我正在尝试检查
textbox2.Text
包含非整数的任何内容。 This is an incredibly inefficient way of doing it, but it's the only way I could figure out. 这是一种极其低效的方法,但这是我唯一能想到的方法。 Is there anything better that I could do?
有什么我能做的更好的吗?
char[] ca = textBox2.Text.ToCharArray();
foreach (char c in ca)
{
string s = "1234567890";
char[] ca2 = s.ToCharArray();
if (c != ca2[0] && c != ca2[1] && c != ca2[2] && c != ca2[3] && c != ca2[4] &&
c != ca2[5] && c != ca2[6] && c != ca2[7] && c != ca2[8] && c != ca2[9])
{
MessageBox.Show("Non-integer detected in text box.");
EndInvoke(null);
}
}
int i = int.Parse(textBox2.Text);
Starting with your code, there is a bunch of things wrong 从您的代码开始,有很多错误
0123456789
for every character, you could have done that once outside the loop 0123456789
的数组,一旦在循环外就可以完成操作 char.IsDigit
char.IsDigit
char[] ca = textBox2.Text.ToCharArray();
foreach (char c in ca)
{
if(!char.IsDigit(c))
{
MessageBox.Show("Non-integer detected in text box.");
EndInvoke(null);
}
}
But you dont even need to do the loop yourself, you can use a Linq method to check Any
elements satisfy for a boolean condition 但是您甚至不需要自己执行循环,您可以使用Linq方法来检查
Any
满足布尔条件的元素
var hasAnyNumbers = textBox2.Text.ToCharArray().Any(char.IsDigit);
But at that point you're trying to parse it to an integer, so I suspect what you meant to ask is "How do I check all the characters are integers" - which is kind of the opposite 但是在那一刻,您正在尝试将其解析为整数,因此我怀疑您想问的是“如何检查所有字符是否为整数”-恰恰相反
var isAllNumbers = textBox2.Text.ToCharArray().All(char.IsDigit);
But, as the other answer states - theres a method for that - int.TryParse
. 但是,正如其他答案所指出的那样,有一种方法可以使用
int.TryParse
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.