英文:
Check if string exists in ArrayList
问题
我有一个包含不同游戏类型的ArrayList:
List<String> availableGenres = new ArrayList<>(Arrays.asList("Arcade", "Puzzle", "Racing", "Casual",
"Strategy", "Sport"));
我想要检查传入的字符串是否存在于这个ArrayList中。使用contains
方法是简单的,比如传入"Sport":
if (availableGenres.contains(game.getGenre())){
...
这是真的
}
但有时候传入的字符串包含了这些值中的多个,比如:"Puzzle Arcade",而这个方法会返回false,但实际上是true。如何处理这种情况呢?
英文:
I have an ArrayList with genres:
List<String> availableGenres = new ArrayList<>(Arrays.asList("Arcade", "Puzzle", "Racing", "Casual",
"Strategy", "Sport")
);
I want to check if incoming string exists in this ArrayList. Okay, it's simple with contains, incoming "Sport":
if (availableGenres.contains(game.getGenre())){
...
this true
}
But sometimes incoming String contains both of these values, like this: "Puzzle Arcade" and this method will return false, but it's actually true. How to deal with this case?
答案1
得分: 2
你可以做的是使用空白字符拆分输入,然后检查ArrayList
中的任何值是否包含任何输入值。
String input = "Puzzle Arcade";
boolean contains = Stream.of(input.split(" "))
.anyMatch(availableGenres::contains);
值得注意的是,如果值是唯一的(包括区分大小写),你也可以使用字符串的集合(Set)而不是列表(List)。
英文:
What you can do is split the input using whitespace and then check if any of the values in the ArrayList
contain any of the input value(s).
String input = "Puzzle Arcade";
boolean contains = Stream.of(input.split(" "))
.anyMatch(availableGenres::contains);
It is worth noting that you could also use a Set of String instead of a List if the values are unique (include case-sensitive).
答案2
得分: 0
如果您想明确检查用户提供的字符串中哪个单词匹配的话:
str = "Puzzle Arcade";
String[] tokens = str.split("\\s+");
for each(String word : tokens){
if (availableGenres.contains(word)){
// 如果您想要的话,标记出现的单词
// TRUE;
}
}
英文:
If you want to explicitly check which word matches in the user-given string
str = "Puzzle Arcade";
String[] tokens = str.split("\\s+");
for each(String word : tokens){
if (availableGenres.contains(word)){
//mark which word was present if you want to
//TRUE;
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论