I'm posting two solutions for LeetCode's "Defanging an IP Address". If you'd like to review, please do. Thank you!
Problem
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 1
#include <stdio.h>
#include <stdlib.h>
static const char* defangIPaddr(
char* address
) {
char* ipv4_memory = calloc(1, sizeof("###[.]###[.]###[.]###"));
char* defanged = ipv4_memory;
for (char* character = address; *character; character++) {
if (*character == '.') {
*ipv4_memory++ = '[';
*ipv4_memory++ = '.';
*ipv4_memory++ = ']';
} else {
*ipv4_memory++ = *character;
}
}
return defanged;
}
int main() {
printf ("%s \n", defangIPaddr("1.1.1.1"));
printf ("%s \n", defangIPaddr("255.100.50.0"));
return 0;
}
Code 2 without changing the input:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static const char* defangIPaddr(
const char* address
) {
char* cloned_address = NULL;
cloned_address = strdup(address);
char* ipv4_memory = calloc(1, sizeof("###[.]###[.]###[.]###"));
char* defanged = ipv4_memory;
for (char* character = cloned_address; *character; character++) {
if (*character == '.') {
*ipv4_memory++ = '[';
*ipv4_memory++ = '.';
*ipv4_memory++ = ']';
} else {
*ipv4_memory++ = *character;
}
}
return defanged;
}
int main() {
printf ("%s \n", defangIPaddr("1.1.1.1"));
printf ("%s \n", defangIPaddr("255.100.50.0"));
return 0;
}
char* address
arg, so neither one modifies its input. You could change it toconst char *address
and it would still compile. Some answers made that point implicitly, but I didn't see a clear mention of that important point that seems to be a sign of some kind of misunderstanding. (Although it seemed too small to post a separate answer.) \$\endgroup\$