给定一个(char *
)字符串,我希望找到一个子字符串的所有匹配项,并将它们替换为一个备用字符串。我在<string.h>
中看不到任何简单的函数来实现这一点。
发布于 2009-04-23 01:28:06
优化器应该消除大多数局部变量。tmp指针用于确保strcpy不必遍历字符串来查找null。tmp在每次调用后指向结果的末尾。(请参阅Shlemiel the painter's algorithm,了解为什么strcpy会令人讨厌。)
// You must free the result if result is non-NULL.
char *str_replace(char *orig, char *rep, char *with) {
char *result; // the return string
char *ins; // the next insert point
char *tmp; // varies
int len_rep; // length of rep (the string to remove)
int len_with; // length of with (the string to replace rep with)
int len_front; // distance between rep and end of last rep
int count; // number of replacements
// sanity checks and initialization
if (!orig || !rep)
return NULL;
len_rep = strlen(rep);
if (len_rep == 0)
return NULL; // empty rep causes infinite loop during count
if (!with)
with = "";
len_with = strlen(with);
// count the number of replacements needed
ins = orig;
for (count = 0; tmp = strstr(ins, rep); ++count) {
ins = tmp + len_rep;
}
tmp = result = malloc(strlen(orig) + (len_with - len_rep) * count + 1);
if (!result)
return NULL;
// first time through the loop, all the variable are set correctly
// from here on,
// tmp points to the end of the result string
// ins points to the next occurrence of rep in orig
// orig points to the remainder of orig after "end of rep"
while (count--) {
ins = strstr(orig, rep);
len_front = ins - orig;
tmp = strncpy(tmp, orig, len_front) + len_front;
tmp = strcpy(tmp, with) + len_with;
orig += len_front + len_rep; // move to next "end of rep"
}
strcpy(tmp, orig);
return result;
}
发布于 2009-04-23 00:53:44
这在标准C库中没有提供,因为如果替换字符串比被替换字符串更长,那么只给出一个char*,就不能增加分配给该字符串的内存。
您可以使用std::string更轻松地完成此操作,但即使这样,也没有一个单独的函数可以为您完成此操作。
发布于 2009-04-23 00:52:46
根本就没有。
你需要使用像strstr和strcat或strcpy这样的东西来编写你自己的代码。
https://stackoverflow.com/questions/779875
复制相似问题