I have a chararray on global, button and textbox, how do I check if the word in textBox1.Text contains the letters in the chararray?
char[] letters = { 'a', 'e' };
private void button1_Click(object sender, EventArgs e)
{
bool containsAnyLetter = textBox1.Text.IndexOfAny(letters) >= 0;
if (containsAnyLetter == true)
{
MessageBox.Show("your word contains a or e");
}
}
You can do this to see if the string contains any of the letters:
private void button1_Click(object sender, EventArgs e)
{
bool containsAnyLetter = letters.Any(c => textBox1.Text.Contains(c));
}
Or more simply:
private void button1_Click(object sender, EventArgs e)
{
bool containsAnyLetter = textBox1.Text.IndexOfAny(letters) >= 0;
}
You can use the String.IndexOfAny(char[] anyOf)
method ( MSDN ):
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text.IndexOfAny(letters) >= 0)
{
MessageBox.Show("Your word contains a or e.");
}
}
Also, keep in mind that IndexOfAny is case-sensitive ( a
will not match A
).
If you want to create a case-insensitive method, you could create an extension method:
public static class StringIndexExtensions
{
public static bool CaseSensitiveContainsAny(this char[] matchChars, string textToCheck)
{
return matchChars.Any(c => textToCheck.IndexOf(
c.ToString(CultureInfo.InvariantCulture),
StringComparison.OrdinalIgnoreCase) >= 0);
}
}
Then you could do the following:
private void button1_Click(object sender, EventArgs e)
{
if (letters.CaseSensitiveContainsAny(textBox1.Text))
{
MessageBox.Show("Your word contains a or e.");
}
}
You can use Regex
private void button1_Click(object sender, EventArgs e)
{
if (Regex.IsMatch(textBox1.Text, @"(a|e)"))
{
MessageBox.Show("your word contains a or e");
}
}
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.