Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a method in java named swearFilter(String text, String[] swear) that takes

ID: 3595784 • Letter: W

Question

Write a method in java named swearFilter(String text, String[] swear) that takes two parameters: a String containing some text, and an array of Strings containing a list of "swear words". Your method will return a String containing the text contained in the first String, where each "swear word" is replaced by its first character, followed by a number of stars equal to the its number of characters minus two, followed by its last character. For example, if the swear words are "duck", "ship", and "whole", and the text contains the following story:

Your method would return:

Notice that your method should recognize both uppercase and lowercase characters in a swear word.

Explanation / Answer

SwearFilterTest.java

public class SwearFilterTest {

public static void main(String[] args) {

String text = "A duck was sailing on a ship shipping whole wheat bread. Duck that SHIP!!!";

String swear[] = {"duck", "ship", "whole"};

System.out.println(swearFilter(text, swear));

}

public static String swearFilter(String text, String[] swear) {

String newStr = text;

for(int i=0;i<swear.length;i++) {

int index = text.toLowerCase().indexOf(swear[i].toLowerCase());

while(index != -1) {

String word = newStr.substring(index, index+swear[i].length());

String s = ""+word.charAt(0);

for(int j=1;j<word.length()-1;j++) {

s = s+"*";

}

s = s + word.charAt(word.length()-1);

text = text.replace(word, s);

index = text.toLowerCase().indexOf(swear[i].toLowerCase());

}

}

return text;

}

}

Output:

A d**k was sailing on a s**p s**pping w***e wheat bread. D**k that S**P!!!

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote