Defanging an IP Address

easy string replace scanning

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.

Inputaddress = "1.1.1.1"
Output"1[.]1[.]1[.]1"
Each of the three dots becomes [.]; 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;
}
Time: O(n) Space: O(n)