1. 开始写的一个字符串替换程序。 debug的时候报错:
Stack around the variable ''***“ was corrupted.
说该字符串遭到损害。 所以运行同不过。。 我查了一下, 是因为我 是直接在source 字符数组上做的替换。 所以造成了该错误。。 照理来说字符数组是不会
有这种错误。 可能我写得代码有问题。
后面还是更正过来了,代码如下:
char *str_replace_array(char *src, char *old_str, char *new_str)
{
char *find_postion = strstr(src, old_str);
int old_str_length = strlen(old_str);
int src_length = strlen(src);
if (find_postion)
{
int post_str_length = find_postion - src + old_str_length;
char *tmp_str = (char *)malloc(post_str_length + 1);
tmp_str[post_str_length] = '\0';
strncpy(tmp_str, find_postion + old_str_length, post_str_length);
// 将old_str放到数组里面来
memcpy(find_postion, new_str, strlen(new_str));
// 将post_str放到数组里面来
strncpy(find_postion + strlen(new_str), tmp_str, post_str_length);
std::cout << src << std::endl;
free(tmp_str);
}
return src;
}
2. 我在网上搜索了一下。查到一个c写得字符串替换程序。 它是先申请块内存, 然后将替换前的字符串 + 替换的字符串 + 替换字符串之后的字符串 赋值到该内存块。然后呢, strdup() 该字符串, 返回。。。
源码
char* str_replace(char *dst, char *src, char *old_str, char *new_str)
{
char *pszPeccancy = strstr(src, old_str);
int length_str = strlen(old_str);
if (pszPeccancy)
{
std::cout << "yes, fond it." << std::endl;
char *tmp_str = (char *)malloc(strlen(src) + strlen(new_str) - length_str + 1);
if (tmp_str)
{
// 前段部分的字符串
int len_before = pszPeccancy - src;
strncpy(tmp_str, src, len_before);
tmp_str[len_before] = '\0';
strcat(tmp_str, new_str);
// 后面那段字符串
strcat(tmp_str, pszPeccancy + length_str);
dst = strdup(tmp_str);
free(tmp_str);
}
std::cout << dst << std::endl;
} else
{
std::cout << "no, not fond it." << std::endl;
}
return dst;
}
int main()
{
char *src = "abcde, your sister.";
char *new_str = "fu";
char *old_str = "your";
char *dst = NULL;
dst = str_replace(dst, src, old_str, new_str);
if (dst)
{
std::cout << dst << std::endl;
free(dst);
}
Sleep(5000);
return 0;
}
需要注意的是:strdup() 里面有重新分配内存。 使用的是malloc() 函数, 所以在外面也要记得free()掉该快内存。 否则会有内存泄露的危机。。。。
如有错误, 欢迎指正。。。 谢谢。