Home > Net >  How to check if the String object passed to the method contains at least one of the words from the l
How to check if the String object passed to the method contains at least one of the words from the l

Time:01-24

I need help with creating a method that takes an object of the String type in the input arguments and a list of objects of the String type. The list contains forbidden words. How can I check if the String object passed to the method contains at least one of the words from the list?

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);
            }
        }
    }
}

CodePudding user response:

take a look at streams and lambda exceptions in java 8 or you can simply create a custom regular expression and then use it.

For the regex I've found online this example:

https://regex101.com/r/cM9hD8/1

CodePudding user response:

Looks like you are missing a condition to exit the loop when a forbidden word was found:

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);
        }
    }
  •  Tags:  
  • Related