Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I verify that an array of strings contain a certain string? [duplicate]

Given :

String[] directions = {"UP","DOWN","RIGHT","LEFT","up","down","right","left"};

String input = "Up";

How can I verify that an input from stdin is within the directions array or not ?

I can make a loop and check each item with input using equal ,but I'm looking for a more elegant way.

Regards,Ron

like image 256
JAN Avatar asked Feb 02 '12 00:02

JAN


People also ask

How do you check if a string is repeated in an array?

Check if a String is contained in an Array using indexOf # We used the Array. indexOf method to check if the string two is contained in the array. If the string is not contained in the array, the indexOf method returns -1 , otherwise it returns the index of the first occurrence of the string in the array.

How do you check if an array contains the same value?

To check if all values in an array are equal:Use the Array. every() method to iterate over the array. Check if each array element is equal to the first one. The every method only returns true if the condition is met for all array elements.


2 Answers

Convert the array of valid directions to a list:

List valid = Arrays.asList(directions) 

Or just declare it directly as:

List valid = Arrays.asList("UP", "DOWN", "RIGHT", "LEFT", "up", "down", "right", "left") 

You can then use the contains method:

if (valid.contains(input)) {     // is valid } else {     // not valid } 

Note that this won't match a mixed case input such as "Up" so you might want to store just the uppercase values in the list and then use valid.contains(input.toUpperCase())

like image 84
mikej Avatar answered Sep 19 '22 21:09

mikej


Convert your array to a List and than use the contains method.

List mylist = Arrays.asList(directions);
mylist.contains(input);

The contains method returns:

true if the list contains the specified element.

like image 21
RanRag Avatar answered Sep 20 '22 21:09

RanRag