Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a string contains a specific string using array

Tags:

arrays

c#

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.

like image 951
Reza Taibur Avatar asked Mar 28 '16 12:03

Reza Taibur


People also ask

How do you check if an array contains a specific item?

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.

How do you check if a string contains text from an array of substrings in Java?

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.

Can you use .contains on arrays?

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​.


1 Answers

Use following lambda expression to find if name contains the bad words.

 bool nameHasBadWords = badWordArray.Any(p => name.Contains(p));
like image 107
M.S. Avatar answered Nov 08 '22 17:11

M.S.