如何检查传递给方法的 String 对象是否至少包含列表中的单词之一 - JAVA

How to check if the String object passed to the method contains at least one of the words from the list- JAVA

我需要帮助创建一个方法,该方法在输入参数中采用字符串类型的对象和字符串类型的对象列表。该列表包含禁用词。如何检查传递给方法的字符串对象是否至少包含列表中的一个单词?

public class Filter {
    public static void main(String[] args) {
        wordsFilter("This sentence contains a forbidden word");
    }
    
    private static void wordsFilter(String sentence) {
        List<String> forbiddenWords = new ArrayList<>();
        forbiddenWords.add("forbiddenWord");
        forbiddenWords.add("forbidden word");

        for (String word : forbiddenWords) {
            if (sentence.contains(word)) {
                System.out.println("The content cannot be displayed");
            } else {
                System.out.println(sentence);
            }
        }
    }
}

当发现禁用词时,您似乎缺少退出循环的条件:

private static void wordsFilter(String sentence) {
        List<String> forbiddenWords = new ArrayList<>();
        forbiddenWords.add("forbiddenWord");
        forbiddenWords.add("forbidden word");

        boolean doesContainAnyForbiddenWords = false;

        for (String word : forbiddenWords) {
            if (sentence.contains(word)) {
                doesContainAnyForbiddenWords = true;
                break; // leave the loop
            } else {
                System.out.println(sentence);
            }
        }

        if (doesContainAnyForbiddenWords) {
            System.out.println("The content cannot be displayed");
        } else {
            System.out.println(sentence);
        }
    }

您可以使用 Streams API

轻松做到这一点
Optional<String> potential_forbidden_word = 
    forbiddenWords.stream().filter(word -> sentence.contains(word)).findFirst();
if(potential_forbidden_word.isPresent())
    System.out.println("don't usw: "+potential_forbidden_word.get());
else
    System.out.println("the sentence is clean");

您甚至可以缩短流:

Optional<String> potential_forbidden_word = 
    forbiddenWords.stream().filter(sentence::contains).findFirst();

AS @Adriaan Koster 提到:您可以简单地使用终端操作 anyMatch(Predicate):

boolean contains_forbidden_word = 
    forbiddenWords.stream().anyMatch(sentence::contains);

您可以使用 equalsIgnoreCase() 检查,因为“foo”或“Foo”或“FoO”等也可能被禁止。