Search inside an array of strings
string[] words = {"januar", "februar", "marec", "april", "maj", "junij", "julij",
"avgust", "september", "oktober", "november", "december"};
I have word "ja" for example or "dec". How can I get "januar" or "december" from an array of stri开发者_开发技巧ng? Is there any fast solution?
Thanks.
You can use LINQ:
words.FirstOrDefault(w => w.StartsWith(str, StringComparison.OrdinalIgnoreCase))
If there was no match, this will return null
.
If you're using the newer versions of C# (3.0 and up) you can use LINQ:
// to find a match anywhere in the word
words.Where(w => w.IndexOf(str,
StringComparison.InvariantCultureIgnoreCase) >= 0);
// to find a match at the beginning only
words.Where(w => w.StartsWith(str,
StringComparison.InvariantCultureIgnoreCase));
List<string> words = new List<string>() { "January", "February", "March", "April" };
var result = words.Where(w => w.StartsWith("jan", StringComparison.OrdinalIgnoreCase));
Will find the results that start with whatever criteria you provide, and ignore the case (optional.)
You can Use simple Regular Expressions as well... string[] words = { "januar", "februar", "marec", "april", "maj", "junij", "julij", "avgust", "september","oktober", "november", "december" };
string sPattern = "ja";
foreach (string s in words)
{
if (System.Text.RegularExpressions.Regex.IsMatch(s, sPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase))
{
System.Console.WriteLine(" (match for '{0}' found)", sPattern);
}
}
精彩评论