简体   繁体   中英

Check if string is a specific character, and limit it to one character

I'm making a calculator for my C# class. I'm not allowed to use buttons for operands. There's an operand text box in which the user is supposed to enter "+" for addition, "-" for subtraction, "/" for division, or "*" for multiplication.

I'm trying to find out how to make it where you can only enter one of those four characters, but it also only lets you input one at a time.

I'm pretty new to C#.

Thank you to "TheGeneral" for helping me figure this out, by giving me this link .

I'm not sure why I couldn't find this question on Google.

This is how I did it:

private void TxtOperator_TextChanged(object sender, EventArgs e)
    {
        Regex regex = new Regex(@"[^+^\-^\/^\*^\(^\)]");
        MatchCollection matches = regex.Matches(txtOperator.Text);
        if (matches.Count > 0)
        {
            MessageBox.Show("Please input an operator.");
            txtOperator.Text = "";
        }
    }

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