string[] words = {"januar", "februar", "marec", "april", "maj", "junij", "julij",
"avgust", "september", "oktober", "november", "december"};
我有单词“ja”或“dec”。我如何从字符串数组中获得“januar”或“december”?有任何快速解决方案吗?
THX
答案 0 :(得分:5)
您可以使用LINQ:
words.FirstOrDefault(w => w.StartsWith(str, StringComparison.OrdinalIgnoreCase))
如果没有匹配,则返回null
。
答案 1 :(得分:3)
如果您使用的是较新版本的C#(3.0及更高版本),可以使用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));
答案 2 :(得分:0)
List<string> words = new List<string>() { "January", "February", "March", "April" };
var result = words.Where(w => w.StartsWith("jan", StringComparison.OrdinalIgnoreCase));
将找到以您提供的任何条件开头的结果,并忽略大小写(可选。)
答案 3 :(得分:0)
您也可以使用简单的正则表达式... string [] words = {“januar”,“februar”,“marec”,“april”,“maj”,“junij”,“julij”,“avgust”,“september”,“oktober”,“11月”, “十二月” };
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);
}
}