c# – 使用数组检查字符串是否包含特定字符串

前端之家收集整理的这篇文章主要介绍了c# – 使用数组检查字符串是否包含特定字符串前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我是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);
原文链接:https://www.f2er.com/csharp/243138.html

猜你在找的C#相关文章