I'm trying to search for a string in a string array in C# but I'm not sure how. So, if the array has 50 elements, most of them null, how would I go about searching for a string in the array? For example:
string[] this_array;
this_array = new string[50];
this_array[1] = "One, Two, Three";
this_array[2] = "Foo, Bar, Five";
this_array[3] = null;
How would I go about searching for "Five" in this_array? I understand I have to use a for loop, I'm just not sure of the actual code. I have to find the exact index so I cannot obtain a boolean.
Any help would be much appreciated!
JamieUpdate: Here's my, very incomplete code, so far:
for (array_number = 1; array_number < this_array.Length; array_number++)
{
//no idea what 开发者_如何学Cto put here :S
}
Use Linq. It's the easiest and less error prone way.
Add a using statement to the top:
using System.Linq;
And search like this.
var result = this_array.Where(x => x != null && x.Contains("string to compare"));
if (result != null) System.Writeln(result.First());
Here is some sample code for you. This will find the first index for a matching entry.
int foundIndex = -1;
for(int i=0; i < this_array.Length; ++i)
{
if (!string.IsNullOrEmpty(this_array[i]) && this_array[i].Contains(searchString))
{
foundIndex = i;
break;
}
}
You could try this...
int index = -1;
string find = "Five";
for(int i = 0; i < this_array.Length; i++)
{
if(string.IsNullOrEmpty(this_array[i]))
continue;
if(this_array[i].ToLowerInvariant().Contains(find.ToLowerInvariant()))
{
index = i;
break;
}
}
NOTE: My search is case-insensitive. If you care about the casing of characters the remove both instances of .ToLowerInvariant()
Since this was homework, I'd recommend you familiarize yourself with the methods available in the String class:
String Methods
MSDN is your friend.
for(int i=1;i<this_array.length;i++)
if(this_array[i]!=null)
if(this_array[i].indexOf("Five")>-1
return i;
That is roughtly c# code - I may have made some minor errors. But surely you could achieve this yourself. Also, I think there are probably better ways of doing this.
精彩评论