user397232
user397232

Reputation: 1790

How to check if a particular character exists within a character array

I am using an array within a C# program as follows:

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

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

How do I check each char c to see if it is found within the character array x?

Upvotes: 18

Views: 69455

Answers (4)

Daniel Elliott
Daniel Elliott

Reputation: 22857

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

Using .NET 3.0/3.5; you will need a using System.Linq;

Upvotes: 41

serhio
serhio

Reputation: 28586

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

Upvotes: 1

Konamiman
Konamiman

Reputation: 50273

If I understood correctly, you need to check if c is in x. Then:

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

Upvotes: 10

Darin Dimitrov
Darin Dimitrov

Reputation: 1038780

You could use Array.IndexOf method:

if (Array.IndexOf(x, c) > -1)
{
    // The x array contains the character c
}

Upvotes: 22

Related Questions