Untitled
unknown
java
2 years ago
2.6 kB
9
Indexable
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 or a number, add it to the current word.
if (Character.isLetterOrDigit(c)) {
word.append(c);
}
// If c is not a letter or a number or we're at the end of the input, check the
// current word
// for curse words.
if (!Character.isLetterOrDigit(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 or a number, add it to the result.
if (!Character.isLetterOrDigit(c)) {
result.append(c);
}
}
}
return result.toString();
}
}
Editor is loading...