一个作业,通过题目给好的函数原型构造功能。但是我写出来的总有一点问题,能帮忙看看哪里不对嘛
int str_replace(const char* in, char* out, int outlen, const char* oldstr, const char* newstr)
{
int len_in = 0;//原字符串指针
int len_out = 0;//现在字符串指针
int counts = 0;//替换次数
int len_new = 0;//新字符串长度
for (; *(newstr + len_new) != '\0'; len_new++)
;//求新字符串长度
char str[outlen];//输出字符串数组
while (len_out < outlen - 1) {
if (*(in + len_in) == '\0')
break;//原字符串指向空的时候结束
if (*(in + len_in) != *oldstr || len_out + len_new >= outlen - 1) {//搜索不到要替换的字符串或者输出长度不允许再被代替
str[len_out] = *(in + len_in);
len_in++;
len_out++;
continue;
} else {
int i;
for (i = 1; *(oldstr + i) != '\0'; i++)
if (*(in + len_in + i) != *(oldstr + i))
break;//判断接下来的几个字符是不是匹配
if (*(oldstr + i) == '\0') {//要替换字符串被匹配完,可以替换
counts++;
len_in += i;//忽略被替换的部分
for (int j = 0; j < len_new; j++) {
str[len_out++] = *(newstr + j);
}
} else {
str[len_out] = *(in + len_in);
len_in++;
len_out++;
}
}
}
str[len_out] = '\0';
out = str;
return counts;
}
没办法给main函数,就是看看传参后怎么去实现这个功能,返回替换次数,并修改out指针。我这个写法可能还面临超时