简体   繁体   English

检查文本框中是否有任何字符

[英]check if there is any of the chars inside the textbox

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? 我在全局,按钮和文本框上有一个chararray,如何检查textBox1.Text中的单词是否包含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 ): 您可以使用String.IndexOfAny(char[] anyOf)方法( 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 ). 另外,请记住, IndexOfAny区分大小写aA不匹配)。

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 你可以使用Regex

private void button1_Click(object sender, EventArgs e)
        {
            if (Regex.IsMatch(textBox1.Text, @"(a|e)"))
            {
                MessageBox.Show("your word contains a or e");
            }
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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