如何检查一个特定字符是否存在于字符数组中

18

我在 C# 程序中使用数组,如下所示:

char[] x = {'0','1','2'};
string s = "010120301";

foreach (char c in s)
{
    // check if c can be found within s
}

如何检查每个字符 c 是否在字符数组 x 中被找到?

4个回答

41
if (x.Contains(c))
{
 //// Do Something
}

在使用 .NET 3.0/3.5 时,你需要添加以下代码:using System.Linq;


1
不适用于“byte”,使用Array.IndexOf的答案↓是有效的。 - Hi-Angel

22
你可以使用 Array.IndexOf 方法:
if (Array.IndexOf(x, c) > -1)
{
    // The x array contains the character c
}

10

如果我理解正确,您需要检查 c 是否在 x 中。那么:

if(x.Contains(c)) { ... }

1
string input = "A_123000544654654"; 
string pattern = "[0-9]+";
System.Text.RegularExpressions.Regex.IsMatch(input, pattern);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接