Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在字符串数组中搜索_C# - Fatal编程技术网

C# 在字符串数组中搜索

C# 在字符串数组中搜索,c#,C#,我有“ja”这个词,例如“dec”。如何从字符串数组中获取“一月”或“十二月”?有什么快速的解决办法吗 谢谢。如果您使用的是C#(3.0及以上)的较新版本,您可以使用LINQ: string[] words = {"januar", "februar", "marec", "april", "maj", "junij", "julij", "avgust", "september", "oktober", "november", "december"}; // to find a ma

我有“ja”这个词,例如“dec”。如何从字符串数组中获取“一月”或“十二月”?有什么快速的解决办法吗


谢谢。

如果您使用的是C#(3.0及以上)的较新版本,您可以使用LINQ:

string[] words = {"januar", "februar", "marec", "april", "maj", "junij", "julij",    
"avgust", "september", "oktober", "november", "december"};
// 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:

string[] words = {"januar", "februar", "marec", "april", "maj", "junij", "julij",    
"avgust", "september", "oktober", "november", "december"};
// 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));
如果没有匹配项,则返回
null

List words=new List(){“一月”、“二月”、“三月”、“四月”};
words.FirstOrDefault(w => w.StartsWith(str, StringComparison.OrdinalIgnoreCase))
var result=words.Where(w=>w.StartsWith(“jan”,StringComparison.OrdinalIgnoreCase));

将查找从您提供的任何条件开始的结果,并忽略大小写(可选)。

您也可以使用简单的正则表达式。。。 string[]words={“一月”、“二月”、“三月”、“四月”、“主要”、“六月”、“朱利叶”、“朱利叶”、“阿古斯特”、“九月”、“奥克托伯”、“十一月”、“十二月” };

List<string> words = new List<string>() { "January", "February", "March", "April" };

var result = words.Where(w => w.StartsWith("jan", StringComparison.OrdinalIgnoreCase));

StringComparison
的存在是有原因的。用它<代码>İiı@Slaks-更新为使用IndexOf而不是Contains,因为Contains没有接受StringComparison的重载。还有更好的方法吗?@SLaks-很有趣。这似乎有点疏忽。不过这是一个有用的扩展方法。使用正则表达式进行扩展就像用链锯切苹果一样。