我是c#的新手.我想知道一个字符串,如用户名是否包含特定的单词.我想从数组中获取这些特定的单词.这是一个例子
Console.Write("Name: "); _name = Console.ReadLine(); name = Program.ProperNameMethod( _name); Console.WriteLine(); string[] badWordArray = { "aBadword1","aBadWord2","aBadWord3" }; if (!string.IsNullOrEmpty(name) // Would like to check for the badwordarray aswell)
(更新)
谢谢大家,但是我学习c#只用了大约一个月就无法覆盖lambda或regex了.我稍后会看一下这些代码.
解决方法
您可能需要不区分大小写的验证:
string[] badWordArray = { "aBadword1","aBadWord3" }; Boolean isBadWord = badWordArray .Any(badWord => name.IndexOf(badword,StringComparison.OrdinalIgnoreCase) >= 0);
或者,如果您验证当前的文化
Boolean isBadWord = badWordArray .Any(badWord => name.IndexOf(badWord,StringComparison.CurrentCultureIgnoreCase) >= 0);
Paranoic案例涉及使用这样的正则表达式:
string[] badWordArray = { "aBadword1","aBadWord3" }; // Nasty user wants to be rude but pass typical filters... String name = "A- Bad..WORD..1 !!!"; String line = Regex.Replace(name,@"\W",""); Boolean isBadWord = badWordArray .Any(badWord => line.IndexOf(badWord,StringComparison.OrdinalIgnoreCase) >= 0);