简体   繁体   English

检查一个char是否匹配char数组中的任何char

[英]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 从您的代码开始,有很多错误

  1. You're recrerating your array of 0123456789 for every character, you could have done that once outside the loop 您正在为每个字符递增0123456789的数组,一旦在循环外就可以完成操作
  2. There is a method already to check whether a character is a numeric digit - 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

Use IsLetter : 使用IsLetter

bool containNonLetter = textBox2.Text.Any(c => !char.IsLetter(c));

But as your goal is to parse it to an int use instead TryParse : 但由于您的目标是将其解析为int而不是TryParse

int result;
if(int.TryParse(textBox2.Text,out result))
{
    //Use result
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM