Defanging an IP Address
Problem
Given a valid IPv4 IP address, return its defanged version. A defanged IP address replaces every period "." with the three-character string "[.]". Every other character is copied unchanged.
address = "1.1.1.1""1[.]1[.]1[.]1"[.]; the digits stay where they are.def defangIPaddr(address):
out = [] # collect output pieces
for ch in address: # scan every character
if ch == ".": # a period?
out.append("[.]") # replace it with [.]
else:
out.append(ch) # keep the character as-is
return "".join(out) # stitch the pieces together
function defangIPaddr(address) {
let out = ""; // build the result string
for (const ch of address) { // scan every character
if (ch === ".") { // a period?
out += "[.]"; // replace it with [.]
} else {
out += ch; // keep the character as-is
}
}
return out;
}
String defangIPaddr(String address) {
StringBuilder out = new StringBuilder(); // build the result
for (char ch : address.toCharArray()) { // scan every character
if (ch == '.') { // a period?
out.append("[.]"); // replace it with [.]
} else {
out.append(ch); // keep the character as-is
}
}
return out.toString();
}
string defangIPaddr(string address) {
string out; // build the result string
for (char ch : address) { // scan every character
if (ch == '.') { // a period?
out += "[.]"; // replace it with [.]
} else {
out += ch; // keep the character as-is
}
}
return out;
}
Explanation
This is a single-pass string transformation. We walk through the input once, character by character, and assemble a new string as we go.
For each character ch there are only two cases. If ch is a period ".", we do not copy the period itself — instead we append the literal three characters "[.]". For every other character (the digits) we append it unchanged.
Because we never look backward or forward, a simple left-to-right scan handles the whole address. Appending to a list (Python) or a StringBuilder / string (Java, C++) and joining at the end keeps the work linear instead of repeatedly re-allocating with naïve concatenation.
Example: "1.1.1.1" has four digits and three dots. The digits stay put and each dot expands to three characters, so the result "1[.]1[.]1[.]1" has length 4 + 3·3 = 13.
In practice a library replace such as address.replace(".", "[.]") does exactly the same thing in one call, but the explicit scan makes the per-character logic clear.