Search⌘ K
AI Features

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...
Java 25
public class ContentModerator {
public static String smartRedact(String message, String[] bannedWords) {
// Split message into array
String[] words = message.split(" ");
// Loop through the array
for (int i = 0; i < words.length; i++) {
String current = words[i];
boolean isBanned = false;
// Check if current word is in bannedWords
for (int j = 0; j < bannedWords.length; j++) {
if (current.equals(bannedWords[j])) {
isBanned = true;
break;
}
}
// If banned, calculate replacement and update array
if (isBanned) {
StringBuilder replacement = new StringBuilder();
int len = current.length();
if (len > 2) {
// Rule 1: Keep first and last
replacement.append(current.charAt(0));
for (int k = 0; k < len - 2; k++) {
replacement.append("*");
}
replacement.append(current.charAt(len - 1));
} else {
// Rule 2: Mask entirely
for (int k = 0; k < len; k++) {
replacement.append("*");
}
}
// CRITICAL STEP: Overwrite the original word in the array
words[i] = replacement.toString();
}
}
// Rejoin the modified array into a single string
return String.join(" ", words);
}
public static void main(String[] args) {
// Scenario 1: Security
String 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 Language
String 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
}
}
...