2013-07-15 39 views
3

我在全局,按鈕和文本框上有一個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"); 
    } 
} 

回答

7

你可以做到這一點,看看是否字符串包含任何字母:

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; 
} 
+1

如果你需要它包含數組中的所有字母,你可以使用「All」而不是「Any」。 – Caleb

+0

\t錯誤1 \t甲字段初始不能引用非靜態字段,方法或屬性 'WindowsFormsApplication4.Form1.letters' \t C:\用戶\ bilgisayar \桌面\ WindowsFormsApplication4 \ WindowsFormsApplication4 \ Form1.cs中\t WindowsFormsApplication4 – Ali

+0

@HakanErbaslar你必須在你的方法中寫* *代碼。看到我更新的答案。 –

2

可以使用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."); 
    } 
} 

另外請記住,IndexOfAny區分大小寫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."); 
    } 
} 
0

您可以使用Regex

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