Untitled

mail@pastecode.io avatar
unknown
java
a year ago
2.5 kB
1
Indexable
Never
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ProfanityFilter {

    String curseLetters = "*&#$%";

    public void read() {
        Scanner sc = new Scanner(System.in);
        String curseWords = sc.nextLine();
        String[] curseWordsArray = curseWords.split(" ");
        while (sc.hasNextLine()) {
            String sentence = sc.nextLine();
            String replacedSentence = replaceCurseWords(sentence, curseWordsArray, curseLetters);
            System.out.println(replacedSentence);
        }
        sc.close();
    }

    public static String replaceCurseWords(String input, String[] curseWords, String pattern) {
        StringBuilder result = new StringBuilder();
        StringBuilder word = new StringBuilder();

        for (int i = 0; i < input.length(); i++) {
            char c = input.charAt(i);

            // If c is a letter, add it to the current word.
            if (Character.isLetter(c)) {
                word.append(c);
            }

            // If c is not a letter or we're at the end of the input, check the current word
            // for curse words.
            if (!Character.isLetter(c) || i == input.length() - 1) {
                if (word.length() > 0) {
                    String lowerCaseWord = word.toString().toLowerCase();

                    // Check if the word is exactly one of the curse words.
                    boolean isCurseWord = false;
                    for (String curseWord : curseWords) {
                        if (lowerCaseWord.equals(curseWord.toLowerCase())) {
                            isCurseWord = true;
                            break;
                        }
                    }

                    // If the word is a curse word, replace letters in the word with the pattern.
                    if (isCurseWord) {
                        for (int j = 0; j < word.length(); j++) {
                            result.append(pattern.charAt(j % pattern.length()));
                        }
                    } else {
                        result.append(word);
                    }
                    word.setLength(0); // Clear the word.
                }

                // If c is not a letter, add it to the result.
                if (!Character.isLetter(c)) {
                    result.append(c);
                }
            }
        }

        return result.toString();
    }
}