我对这段代码有两个问题(我可以看到 - ; ^):
1)如果不满足条件1,则两个验证消息框都显示;我只希望显示一个或另一个给定每个if块的条件。
2)如何验证字符串中相同的大写和小写字符(如果是第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();
}
}
答案 0 :(得分:0)
对于第一部分,只需使用else if
- 然后只有第一个块不是第二个块才会执行。
对于第二部分,您可以使用ToLower
或ToUpper
,这样您就可以比较同一案例中的所有字符。
所以,结合这两个变化:
else if (textBox3.Text.ToUpper().Distinct().Count() == 5)
答案 1 :(得分:0)
您要验证文本框不应超过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
}