URL
链接:https://leetcode.cn/problems/defanging-an-ip-address/
题目
![截图](https://img-blog.csdnimg.cn/e7abde7293914fa89e68f36092bfdb6e.png)
分析
![截图](https://img-blog.csdnimg.cn/ba5629a502d2428ba54ea6da3cdd4a78.png)
源码
工程结构
.
└── main_1108.c
源码文件
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char * defang_ipaddr(char * addr){
int len = strlen(addr);
int pos = 0;
char * res = (char *)malloc(sizeof(char) * (len + 7));
for (int i = 0; i < len; ++i) {
if (addr[i] == '.') {
pos += sprintf(res + pos, "%s", "[.]");
} else {
res[pos++] = addr[i];
}
}
res[pos] = '\0';
return res;
}
int main()
{
char ori[] = "255.100.50.0";
char * res = defang_ipaddr(ori);
printf("ori : %s\n", ori);
printf("res : %s\n", res);
free(res);
return 0;
}
LOG参考
ori : 255.100.50.0
res : 255[.]100[.]50[.]0
源码概述
- 申请内存,存储原始字符串,匹配到的字符串用新子串替换strcat的方式。
小结
- 不要舍不得用内存!