简体   繁体   中英

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. 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
  2. There is a method already to check whether a character is a numeric digit - 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

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 .

Use 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 result;
if(int.TryParse(textBox2.Text,out result))
{
    //Use result
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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