我需要一段C++中在一个字符串中替换特定字符串的代码
时间: 2023-03-15 09:59:31 浏览: 98
你可以使用以下代码来替换特定字符串:
char *str_replace(char *orig, char *rep, char *with) {
char *result;
int len_rep;
int len_with;
int len_front;
int count;
char *tmp;
int i;
if (!orig || !rep)
return NULL;
len_rep = strlen(rep);
if (len_rep == 0)
return NULL;
if (!with)
with = "";
len_with = strlen(with);
tmp = orig;
for (count = 0; tmp = strstr(tmp, rep); ++count) {
tmp += len_rep;
}
tmp = result = malloc(strlen(orig) + (len_with - len_rep) * count + 1);
if (!result)
return NULL;
while (count--) {
tmp = strstr(orig, rep);
len_front = tmp - orig;
tmp = strncpy(tmp, with, len_with) + len_with;
orig += len_front + len_rep;
}
strcpy(tmp, orig);
return result;
}
阅读全文