URL
链接:https://leetcode.cn/problems/defanging-an-ip-address/
题目
分析
源码
工程结构
.
└── main_1108.c
源码文件
/* main.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[] = "1.1.1.1";
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的方式。
小结
- 不要舍不得用内存!