可以使用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.");
}
}
如果你需要它包含數組中的所有字母,你可以使用「All」而不是「Any」。 – Caleb
\t錯誤1 \t甲字段初始不能引用非靜態字段,方法或屬性 'WindowsFormsApplication4.Form1.letters' \t C:\用戶\ bilgisayar \桌面\ WindowsFormsApplication4 \ WindowsFormsApplication4 \ Form1.cs中\t WindowsFormsApplication4 – Ali
@HakanErbaslar你必須在你的方法中寫* *代碼。看到我更新的答案。 –