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

[亡魂溺海] 提交于 2019-12-21 03:25:20

问题


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


回答1:


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())




回答2:


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.




回答3:


Unfortunately, Java does not have an Arrays.indexOf() method. Your best bet is to write a little utility to do a simple linear search. Or you could convert to an ArrayList (see Arrays.asList()) and call indexOf() or contains().

If the array is large and speed is a concern, you could sort the array, and then use Arrays.binarySearch().




回答4:


Use ArrayList instead and its contains method




回答5:


Since we are specifically talking about arrays of strings, not just any array: another approach which solves the case-insensitivity question elegantly would be using regular expressions. Either through the Pattern class or the String's matches method.

if (input.matches("(?i)" + String.join("|", directions))) {
    // valid
}
else {
    // invalid
}


来源:https://stackoverflow.com/questions/9105358/how-can-i-verify-that-an-array-of-strings-contain-a-certain-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!