Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

c#

.net

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?

like image 433
user397232 Avatar asked Nov 30 '09 08:11

user397232


People also ask

How do you check if a character is in a character array?

contains() method with Examples. The contains() method of Chars Class in Guava library is used to check if a specified value is present in the specified array of char values. The char value to be searched and the char array in which it is to be searched, are both taken as a parameter.

How do you check if a character is present in an array in C?

The strpbrk function returns a pointer to the character, or a null pointer if no character from s2 occurs in s1. The question asks about 'for each char in string ... if it is in list of invalid chars'. With these functions, you can write: size_t len = strlen(test); size_t spn = strcspn(test, "invald"); if (spn !=

How do I check if a char array is empty?

The easiest/fastest way to ensure that a C string is initialized to the empty string is to simply set the first byte to 0. char text[50]; text[0] = 0; From then, both strlen(text) and the very-fast-but-not-as-straightforward (text[0] == 0) tests will both detect the empty string.

Can you have an array of characters?

A character array is a sequence of characters, just as a numeric array is a sequence of numbers. A typical use is to store a short piece of text as a row of characters in a character vector.


2 Answers

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

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

like image 113
Daniel Elliott Avatar answered Oct 13 '22 14:10

Daniel Elliott


You could use Array.IndexOf method:

if (Array.IndexOf(x, c) > -1)
{
    // The x array contains the character c
}
like image 22
Darin Dimitrov Avatar answered Oct 13 '22 13:10

Darin Dimitrov