How to search a
string in String array in C#
1. Using Array.Find()
static void
SearchInArray() { string[]
names = { "DotNet", "Munesh
Sharma", "Kishan", "Ravi", "Mohan", "Rahul", "Govind" }; var
stringToFind = "Rahul"; var
result = Array.Find(names, x => x == stringToFind);
Console.WriteLine(result); }
Output
2. Search string which start from a character
static void
SearchInArray() { string[]
names = { "DotNet", "Munesh
Sharma", "Kishan", "Ravi", "Mohan", "Rahul", "Govind" }; var
result = Array.Find(names, x => x.StartsWith("R"));
Console.WriteLine(result[1]); }
the result will be Ravi and the reason is we are search string which start from R and we are using Find method ,hence giving first string it find.
if we want all the string which start from R then we have to use FindAll method like below
static void
SearchInArray() { string[]
names = { "DotNet", "Munesh
Sharma", "Kishan", "Ravi", "Mohan", "Rahul", "Govind" }; var
result = Array.FindAll(names, x => x.StartsWith("R")); foreach (var
item in result) {
Console.WriteLine(item); } }
Output
3. Search string by length
static void
SearchInArray() { string[] names
= { "DotNet", "Munesh
Sharma", "Kishan", "Ravi", "Mohan", "Rahul", "Govind" }; var
result = Array.FindAll(names, x => x.Length > 5); foreach (var
item in result) {
Console.WriteLine(item); } }
output
EmoticonEmoticon