Defanging an IP Address
Problem
You are given a valid IPv4 address as a string. Defang it by replacing every period character "." with the string "[.]". Return the resulting string.
address = "1.1.1.1""1[.]1[.]1[.]1"def defang_ip_addr(address):
out = []
for ch in address:
if ch == '.':
out.append('[.]')
else:
out.append(ch)
return ''.join(out)
function defangIPaddr(address) {
let out = "";
for (const ch of address) {
if (ch === ".") out += "[.]";
else out += ch;
}
return out;
}
class Solution {
public String defangIPaddr(String address) {
StringBuilder out = new StringBuilder();
for (char ch : address.toCharArray()) {
if (ch == '.') out.append("[.]");
else out.append(ch);
}
return out.toString();
}
}
string defangIPaddr(string address) {
string out;
for (char ch : address) {
if (ch == '.') out += "[.]";
else out += ch;
}
return out;
}
Explanation
"Defanging" just means making an IP address harmless to click by turning every dot into the token [.]. The solution is a straightforward single scan that copies the string while swapping the dots.
We build the answer in a list (or string builder) called out. Walking character by character, whenever we see a period '.' we append the three-character string "[.]"; for any other character we append it unchanged.
Using a list and joining at the end avoids repeatedly recreating an immutable string, which keeps it efficient and clear.
Because each input character produces a fixed output, the work is linear in the length of the address.
Example: "1.1.1.1" becomes "1[.]1[.]1[.]1" — each of the three dots expands to [.] while the digits are copied as-is.