Untitled
unknown
java
2 years ago
2.8 kB
8
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, 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 contains any of the curse words.
for (String curseWord : curseWords) {
if (lowerCaseWord.contains(curseWord.toLowerCase())) {
// Replace letters in the word with the pattern.
for (int j = 0; j < word.length(); j++) {
if (Character.isLetter(word.charAt(j))) {
result.append(pattern.charAt(j % pattern.length()));
} else {
result.append(word.charAt(j));
}
}
word.setLength(0); // Clear the word.
break;
}
}
// If the word was not replaced, add it to the result.
if (word.length() > 0) {
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();
}
}
Editor is loading...