[英]search inside array of strings
string[] words = {"januar", "februar", "marec", "april", "maj", "junij", "julij",
"avgust", "september", "oktober", "november", "december"};
我有单词“ja”或“dec”。 我如何从字符串数组中获得“januar”或“december”? 有什么快速的解决方案
谢谢
您可以使用LINQ:
words.FirstOrDefault(w => w.StartsWith(str, StringComparison.OrdinalIgnoreCase))
如果没有匹配,则返回null
。
如果您使用的是较新版本的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));
List<string> words = new List<string>() { "January", "February", "March", "April" };
var result = words.Where(w => w.StartsWith("jan", StringComparison.OrdinalIgnoreCase));
将找到以您提供的任何条件开头的结果,并忽略大小写(可选。)
您也可以使用简单的正则表达式... string [] words = {“januar”,“februar”,“marec”,“april”,“maj”,“junij”,“julij”,“avgust”,“ 9月“,”oktober“,”11月“,”12月“};
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.