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; }
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.
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.
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.
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.
Just use the already built-in Contains() method:
using System.Linq; //... string[] array = { "foo", "bar" }; if (array.Contains("foo")) { //... }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With