Algorithm
Problem Name: 1108. Defanging an IP Address
Given a valid (IPv4) IP address
, return a defanged version of that IP address.
A defanged IP address replaces every period "."
with "[.]"
.
Example 1:
Input: address = "1.1.1.1" Output: "1[.]1[.]1[.]1"
Example 2:
Input: address = "255.100.50.0" Output: "255[.]100[.]50[.]0"
Constraints:
- The given
address
is a valid IPv4 address.
Code Examples
#1 Code Example with Java Programming
Code -
Java Programming
class Solution {
public String defangIPaddr(String address) {
StringBuilder sb = new StringBuilder();
for (char c : address.toCharArray()) {
sb.append(c == '.' ? "[.]" : c);
}
return sb.toString();
}
}
Copy The Code &
Try With Live Editor
Input
Output
#2 Code Example with Javascript Programming
Code -
Javascript Programming
const defangIPaddr = function(address) {
return address.split('.').join('[.]')
};
Copy The Code &
Try With Live Editor
Input
Output
#3 Code Example with Python Programming
Code -
Python Programming
class Solution:
def defangIPaddr(self, address: str) -> str:
return address.replace(".", "[.]")
Copy The Code &
Try With Live Editor
Input
Output
#4 Code Example with C# Programming
Code -
C# Programming
using System.Text;
namespace LeetCode
{
public class _1108_DefangingAnIPAddress
{
public string DefangIPaddr(string address)
{
var sb = new StringBuilder();
foreach (var ch in address)
{
if (ch == '.')
sb.Append("[.]");
else
sb.Append(ch);
}
return sb.ToString();
}
}
}
Copy The Code &
Try With Live Editor
Input
Output