Solution: Sensitive Data Redactor
Explore how to manipulate strings and arrays in Java to redact sensitive data. This lesson teaches splitting text, scanning for banned words, and replacing them with asterisks using StringBuilder to securely handle sensitive information.
We'll cover the following...
We'll cover the following...
Java 25
public class ContentModerator {public static String smartRedact(String message, String[] bannedWords) {// Split message into arrayString[] words = message.split(" ");// Loop through the arrayfor (int i = 0; i < words.length; i++) {String current = words[i];boolean isBanned = false;// Check if current word is in bannedWordsfor (int j = 0; j < bannedWords.length; j++) {if (current.equals(bannedWords[j])) {isBanned = true;break;}}// If banned, calculate replacement and update arrayif (isBanned) {StringBuilder replacement = new StringBuilder();int len = current.length();if (len > 2) {// Rule 1: Keep first and lastreplacement.append(current.charAt(0));for (int k = 0; k < len - 2; k++) {replacement.append("*");}replacement.append(current.charAt(len - 1));} else {// Rule 2: Mask entirelyfor (int k = 0; k < len; k++) {replacement.append("*");}}// CRITICAL STEP: Overwrite the original word in the arraywords[i] = replacement.toString();}}// Rejoin the modified array into a single stringreturn String.join(" ", words);}public static void main(String[] args) {// Scenario 1: SecurityString msg1 = "My password is password123";String[] banned1 = {"password", "password123"};System.out.println("--- Security Check ---");System.out.println("Original: " + msg1);System.out.println("Redacted: " + smartRedact(msg1, banned1));// Expected: My p******d is p*********3// Scenario 2: Abusive LanguageString msg2 = "You are stupid and ugly";String[] banned2 = {"stupid", "ugly", "bad"};System.out.println("\n--- Moderation Check ---");System.out.println("Original: " + msg2);System.out.println("Redacted: " + smartRedact(msg2, banned2));// Expected: You are s****d and u**y}}
...