Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 检查文本框中是否有任何字符_C#_String_Winforms - Fatal编程技术网

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

C# 检查文本框中是否有任何字符,c#,string,winforms,C#,String,Winforms,我在全局、按钮和文本框上有一个字符集,如何检查文本框1中的单词是否包含字符集中的字母 char[] letters = { 'a', 'e' }; private void button1_Click(object sender, EventArgs e) { bool containsAnyLetter = textBox1.Text.IndexOfAny(letters) >= 0; if (containsAnyLetter == true) {

我在全局、按钮和文本框上有一个字符集,如何检查文本框1中的单词是否包含字符集中的字母

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");
    }
}

您可以执行此操作以查看字符串是否包含以下任何字母:

private void button1_Click(object sender, EventArgs e)
{
    bool containsAnyLetter = letters.Any(c => textBox1.Text.Contains(c));
}
或者更简单地说:

private void button1_Click(object sender, EventArgs e)
{
    bool containsAnyLetter = textBox1.Text.IndexOfAny(letters) >= 0;
}

您可以使用
String.IndexOfAny(char[]anyOf)
方法():

另外,请记住,索引是区分大小写的(
a
a
不匹配)

如果要创建不区分大小写的方法,可以创建扩展方法:

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);
    }
}
然后您可以执行以下操作:

private void button1_Click(object sender, EventArgs e)
{
    if (letters.CaseSensitiveContainsAny(textBox1.Text))
    {
        MessageBox.Show("Your word contains a or e.");
    }
}

您可以使用
Regex

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

如果需要包含数组中的所有字母,可以使用“all”而不是“Any”。错误1字段初始值设定项不能引用非静态字段、方法,或属性“WindowsFormsApplication4.Form1.letters”C:\Users\bilgisayar\Desktop\WindowsFormsApplication4\WindowsFormsApplication4\Form1.cs 22 34WindowsFormsApplication4@HakanErbaslar您必须在方法内部编写该代码。请参阅我的最新答案。
private void button1_Click(object sender, EventArgs e)
        {
            if (Regex.IsMatch(textBox1.Text, @"(a|e)"))
            {
                MessageBox.Show("your word contains a or e");
            }
        }