在字符串数组内搜索
问题描述:
string[] words = {"januar", "februar", "marec", "april", "maj", "junij", "julij",
"avgust", "september", "oktober", "november", "december"};
例如,我有单词“ja”或“dec”。我如何从字符串数组中获得“januar”或“12月”?有没有快速解决方案?在字符串数组内搜索
THX
答
如果您正在使用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));
答
你可以使用LINQ:
words.FirstOrDefault(w => w.StartsWith(str, StringComparison.OrdinalIgnoreCase))
如果有没有匹配,这将返回null
。
答
List<string> words = new List<string>() { "January", "February", "March", "April" };
var result = words.Where(w => w.StartsWith("jan", StringComparison.OrdinalIgnoreCase));
会发现,你提供力所能及的条件开始结果,而忽略的情况下(可选)。
答
您可以使用简单的正则表达式,以及... 的String []字= {“ januar“,”februar“,”marec“,”april“,”maj“,”junij“,”julij“,”avgust“,”九月“,”oktober“,”十一月“,”十二月“ }
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);
}
}
+2
这样做与正则表达式就像使用电锯切片苹果。 – SLaks 2010-06-29 14:44:49
'StringComparison'存在是有原因的。 **用它**! '我我I'' – SLaks 2010-06-29 14:26:19
@SLaks - 已经更新。 – 2010-06-29 14:29:01
@Slaks - 已更新为使用IndexOf而不是Contains,因为Contains没有接受StringComparison的重载。有没有更好的办法? – 2010-06-29 14:34:02