Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search a string in String array

Tags:

c#

asp.net

I need to search a string in the string array. I dont want to use any for looping in it

string [] arr = {"One","Two","Three"};  string theString = "One" 

I need to check whether theString variable is present in arr.

like image 580
balaweblog Avatar asked Nov 05 '08 12:11

balaweblog


People also ask

How do I check if a string exists in an array?

Check if a String is contained in an Array using indexOf #indexOf method to check if the string two is contained in the array. If the string is not contained in the array, the indexOf method returns -1 , otherwise it returns the index of the first occurrence of the string in the array.

How do you search inside an array?

Use filter if you want to find all items in an array that meet a specific condition. Use find if you want to check if that at least one item meets a specific condition. Use includes if you want to check if an array contains a particular value. Use indexOf if you want to find the index of a particular item in an array.

How do I find a string in an array C++?

Simply use this function. std::find(std::begin(tab), std::end(tab), n); will return an iterator to the element if it was found, the end iterator otherwise. Checking for equality with the end iterator will tell you if the element was found in the array.

How do you check if a string is in a array C?

You have to iterate through x and do strcmp on each element of array x, to check if s is the same as one of the elements of x.


1 Answers

Well, something is going to have to look, and looping is more efficient than recursion (since tail-end recursion isn't fully implemented)... so if you just don't want to loop yourself, then either of:

bool has = arr.Contains(var); // .NET 3.5 

or

bool has = Array.IndexOf(arr, var) >= 0; 

For info: avoid names like var - this is a keyword in C# 3.0.

like image 122
Marc Gravell Avatar answered Oct 15 '22 19:10

Marc Gravell