V
V
Vladislav2020-08-17 21:06:37
C++ / C#
Vladislav, 2020-08-17 21:06:37

Need to compare an array with a variable and return true or false?

There is an array "Items" it should be compared with the variable "choice" and return true or false depending on the result if the words match then true otherwise false
public string[]= Items { "Box", "Bottle" , "Phone" };

string select = Console.ReadLine();

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Peter, 2020-08-17
@Vladlen234

Get a separate variable for user input, then in a loop compare what the user entered with the contents of the array.
You can even wrap it in a function. Which will take a string and, for example, the desired array. And return you true or false.

As an option

static void Main(string[] args)
        {
            string[] items = { "Коробка", "Бутылка", "Телефон" };

            Console.WriteLine("Введите слово:");
            string user_input = Console.ReadLine();


            Console.WriteLine(isExist(user_input, items));

            Console.ReadKey();
        }


        static bool isExist(string user_input, string [] arr)
        {
            foreach(var word in arr)
            {
                if (word == user_input)
                    return true;
            }

            return false;
        }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question