如何验证字符串中相同、重复的大写和小写字符

本文关键字:字符 何验证 验证 字符串 | 更新日期: 2023-09-27 17:55:14

我对这段代码有两个问题(我可以看到 - ;^):

1)如果不满足条件一,则显示两个验证消息框;我只希望显示一个或另一个给定每个 if 块中的条件。

2)如何验证(如果是块二)字符串中的相同大写和小写字符?

public partial class Substrings : Form
{
    public Substrings()
    {
        InitializeComponent();
    }
    private void buttonGo_Click(object sender, EventArgs e)
    {
        //validate input for 5 characters and same characters with Equals method
        if (textBox3.TextLength != 5)
        {
            MessageBox.Show("The string must have exactly 5 characters, try again");
            textBox3.Clear();
            textBox3.Focus();
        }
        //validate only unique characters in string
        if (textBox3.Text.Distinct().Count() == 5)
        {
            listBox1.Items.Add(textBox3.Text.Substring(0, 1)); //p
            listBox1.Items.Add(textBox3.Text.Substring(1, 1)); //o
            listBox1.Items.Add(textBox3.Text.Substring(2, 1)); //w
            listBox1.Items.Add(textBox3.Text.Substring(3, 1)); //e
            listBox1.Items.Add(textBox3.Text.Substring(4, 1)); //r
            listBox1.Items.Add(textBox3.Text.Substring(0, 2)); //Po
            listBox1.Items.Add(textBox3.Text.Substring(1, 2)); //ow
            listBox1.Items.Add(textBox3.Text.Substring(2, 2)); //we
            listBox1.Items.Add(textBox3.Text.Substring(3, 2)); //er
            listBox1.Items.Add(textBox3.Text.Substring(0, 3)); //Pow
            listBox1.Items.Add(textBox3.Text.Substring(1, 3)); //owe
            listBox1.Items.Add(textBox3.Text.Substring(2, 3)); //wer
            listBox1.Items.Add(textBox3.Text.Substring(0, 4)); //Powe
            listBox1.Items.Add(textBox3.Text.Substring(1, 4)); //ower
            listBox1.Items.Add(textBox3.Text.Substring(0, 5)); //Power
        }
        else
            MessageBox.Show("The string must have distinct, non-repeating characters");
    }
    private void textBox3_TextChanged(object sender, EventArgs e)
    {
    }
    private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
    }
    private void buttonExit_Click(object sender, EventArgs e)
    {
        Application.Exit();
    }
}

如何验证字符串中相同、重复的大写和小写字符

对于第一部分,只需使用 else if - 那么第二个块只有在第一个块没有时才会被执行。

对于第二部分,您可以使用ToLowerToUpper,以便在同一情况下比较所有字符。

因此,结合这两个更改:

else if (textBox3.Text.ToUpper().Distinct().Count() == 5)

您希望验证文本框不应超过 5 个字符,然后验证它是否需要具有唯一字符。你可以试试这个:

//validate input for 5 characters and same characters with Equals method
if (textBox3.Length != 5)
{
    MessageBox.Show("The string must have exactly 5 characters, try again");
    textBox3.Clear();
    textBox3.Focus();
}
//validate only unique characters in string
else if (textBox3.Text.ToLower().Distinct().Count() != textBox3.Text.Length)
{
    MessageBox.Show("The string must have distinct, non-repeating characters");
}
else
{
    // Do your stuffs here
}