question:
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.
Ideas:
1.use StringBuffer,
public String defangIPaddr(String address) {
StringBuffer a =new StringBuffer();
char[] chars = address.toCharArray();
for (int i = 0; i < address.length(); i++) {
if(chars[i]=='.'){
a.append("[.]");
}else{
a.append(chars[i]);
}
}
return a.toString();
}
2.use replace
public class test {
public String defangIPaddr(String address) {
return address.replace(".", "[.]");
}