How to search a string in String array

C#asp.net

C# Problem Overview


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.

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

Every method, mentioned earlier does looping either internally or externally, so it is not really important how to implement it. Here another example of finding all references of target string

       string [] arr = {"One","Two","Three"};
       var target = "One";
       var results = Array.FindAll(arr, s => s.Equals(target));

Solution 3 - C#

Does it have to be a string[] ? A List<String> would give you what you need.

List<String> testing = new List<String>();
testing.Add("One");
testing.Add("Two");
testing.Add("Three");
testing.Add("Mouse");
bool inList = testing.Contains("Mouse");

Solution 4 - C#

bool exists = arr.Contains("One");

Solution 5 - C#

I think it is better to use Array.Exists than Array.FindAll.

Solution 6 - C#

Its pretty simple. I always use this code to search string from a string array

string[] stringArray = { "text1", "text2", "text3", "text4" };
string value = "text3";
int pos = Array.IndexOf(stringArray, value);
if (pos > -1)
{
    return true;
}
else
{
    return false;
}

Solution 7 - C#

If the array is sorted, you can use BinarySearch. This is a O(log n) operation, so it is faster as looping. If you need to apply multiple searches and speed is a concern, you could sort it (or a copy) before using it.

Solution 8 - C#

Each class implementing IList has a method http://msdn.microsoft.com/en-us/library/system.collections.ilist.contains.aspx">Contains(Object value). And so does System.Array.

Solution 9 - C#

Why the prohibition "I don't want to use any looping"? That's the most obvious solution. When given the chance to be obvious, take it!

Note that calls like arr.Contains(...) are still going to loop, it just won't be you who has written the loop.

Have you considered an alternate representation that's more amenable to searching?

  • A good Set implementation would perform well. (HashSet, TreeSet or the local equivalent).
  • If you can be sure that arr is sorted, you could use binary search (which would need to recurse or loop, but not as often as a straight linear search).

Solution 10 - C#

At first shot, I could come up with something like this (but it's pseudo code and assuming you cannot use any .NET built-in libaries). Might require a bit of tweaking and re-thinking, but should be good enough for a head-start, maybe?

int findString(String var, String[] stringArray, int currentIndex, int stringMaxIndex)
    {
    if currentIndex > stringMaxIndex 
       return (-stringMaxIndex-1);
    else if var==arr[currentIndex] //or use any string comparison op or function
       return 0;
    else 
       return findString(var, stringArray, currentIndex++, stringMaxIndex) + 1 ;
    }
    
    
    
    //calling code
    int index = findString(var, arr, 0, getMaxIndex(arr));
    
    if index == -1 printOnScreen("Not found");
    else printOnScreen("Found on index: " + index);

Solution 11 - C#

In C#, if you can use an ArrayList, you can use the Contains method, which returns a boolean:

if MyArrayList.Contains("One")

Solution 12 - C#

You can use Find method of Array type. From .NET 3.5 and higher.

public static T Find<T>(
	T[] array,
	Predicate<T> match
)

Here is some examples:

// we search an array of strings for a name containing the letter “a”:
static void Main()
{
  string[] names = { "Rodney", "Jack", "Jill" };
  string match = Array.Find (names, ContainsA);
  Console.WriteLine (match);     // Jack
}
static bool ContainsA (string name) { return name.Contains ("a"); }

Here’s the same code shortened with an anonymous method:

string[] names = { "Rodney", "Jack", "Jill" };
string match = Array.Find (names, delegate (string name)
  { return name.Contains ("a"); } ); // Jack

A lambda expression shortens it further:

string[] names = { "Rodney", "Jack", "Jill" };
string match = Array.Find (names, n => n.Contains ("a"));     // Jack

Solution 13 - C#

You can check the element existence by

arr.Any(x => x == "One")

Solution 14 - C#

it is old one ,but this is the way i do it ,

enter code herevar result = Array.Find(names, element => element == "One");

Solution 15 - C#

I'm surprised that no one suggested using Array.IndexOf Method.

Indeed, Array.IndexOf has two advantages :

  • It allows searching if an element is included into an array,
  • It gets at the same time the index into the array.
int stringIndex = Array.IndexOf(arr, theString);
if (stringIndex >= 0)
{
    // theString has been found
}

Inline version :

if (Array.IndexOf(arr, theString) >= 0)
{
    // theString has been found
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbalaweblogView Question on Stackoverflow
Solution 1 - C#Marc GravellView Answer on Stackoverflow
Solution 2 - C#TamirView Answer on Stackoverflow
Solution 3 - C#ZombieSheepView Answer on Stackoverflow
Solution 4 - C#mohammednView Answer on Stackoverflow
Solution 5 - C#Joe Cheri RossView Answer on Stackoverflow
Solution 6 - C#Sharp CodersView Answer on Stackoverflow
Solution 7 - C#GvSView Answer on Stackoverflow
Solution 8 - C#VolkerKView Answer on Stackoverflow
Solution 9 - C#bendinView Answer on Stackoverflow
Solution 10 - C#Salman KasbatiView Answer on Stackoverflow
Solution 11 - C#DOKView Answer on Stackoverflow
Solution 12 - C#Yuliia AshomokView Answer on Stackoverflow
Solution 13 - C#AhmadView Answer on Stackoverflow
Solution 14 - C#AliView Answer on Stackoverflow
Solution 15 - C#user12805184View Answer on Stackoverflow