I am new to c#. I would like to know if a string such as a user name contains a specific word. I want to get those specific words from an array.Here's a example.`
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)
(Update)
Thank you all but me learning c# only for about a month could not cover lambda or regex yet. I will have a look at these codes while later.
The simplest and fastest way to check if an item is present in an array is by using the Array. indexOf() method. This method searches the array for the given item and returns its index. If no item is found, it returns -1.
Using String.contains() method for each substring. You can terminate the loop on the first match of the substring, or create a utility function that returns true if the specified string contains any of the substrings from the specified list.
contains() method in Java is used to check whether or not a list contains a specific element. To check if an element is in an array, we first need to convert the array into an ArrayList using the asList() method and then apply the same contains() method to it.
Use following lambda expression to find if name contains the bad words.
bool nameHasBadWords = badWordArray.Any(p => name.Contains(p));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With