Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is string in array?

Tags:

arrays

string

c#

What would be the best way to look in a string[] to see if it contains a element. This was my first shot at it. But perhaps there is something that I am overlooking. The array size will be no larger than 200 elements.

bool isStringInArray(string[] strArray, string key) {     for (int i = 0; i <= strArray.Length - 1; i++)         if (strArray[i] == key)             return true;     return false; } 
like image 505
Brad Avatar asked Feb 01 '09 17:02

Brad


People also ask

Is string exist in array?

To check if a string is contained in an array, call the includes() method, passing it the string as a parameter. The includes method will return true if the string is contained in the array and false otherwise. Copied! We used the Array.

Is string and array are same?

The key difference between Array and String is that an Array is a data structure that holds a collection of elements having the same data types, while a String is a collection of characters.

Is string in JS an array?

Unfortunately, JavaScript strings aren't quite arrays. They look and act a little bit like arrays, but they're missing a few of the useful methods. Notice that, when indexing, it returns a one-character string, not a single character.

Why is a string an array?

Strings are declared similarly as arrays with the exception of char type. String is a contiguous sequence of values with a common name. Unlike arrays, strings are immutable which means their values cannot be modified once they are assigned.


2 Answers

Just use the already built-in Contains() method:

using System.Linq;  //...  string[] array = { "foo", "bar" }; if (array.Contains("foo")) {     //... } 
like image 181
Dave Markle Avatar answered Oct 14 '22 08:10

Dave Markle


I know this is old, but I wanted the new readers to know that there is a new method to do this using generics and extension methods.

You can read my blog post to see more information about how to do this, but the main idea is this:

By adding this extension method to your code:

public static bool IsIn<T>(this T source, params T[] values) {     return values.Contains(source); } 

you can perform your search like this:

string myStr = "str3";  bool found = myStr.IsIn("str1", "str2", "str3", "str4"); 

It works on any type (as long as you create a good equals method). Any value type for sure.

like image 34
Gabriel McAdams Avatar answered Oct 14 '22 07:10

Gabriel McAdams