首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在C中,什么函数可以替换字符串的子字符串?

在C中,什么函数可以替换字符串的子字符串?
EN

Stack Overflow用户
提问于 2009-04-23 00:48:50
回答 20查看 319K关注 0票数 108

给定一个(char *)字符串,我希望找到一个子字符串的所有匹配项,并将它们替换为一个备用字符串。我在<string.h>中看不到任何简单的函数来实现这一点。

EN

回答 20

Stack Overflow用户

发布于 2009-04-23 01:28:06

优化器应该消除大多数局部变量。tmp指针用于确保strcpy不必遍历字符串来查找null。tmp在每次调用后指向结果的末尾。(请参阅Shlemiel the painter's algorithm,了解为什么strcpy会令人讨厌。)

代码语言:javascript
复制
// 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;
}
票数 104
EN

Stack Overflow用户

发布于 2009-04-23 00:53:44

这在标准C库中没有提供,因为如果替换字符串比被替换字符串更长,那么只给出一个char*,就不能增加分配给该字符串的内存。

您可以使用std::string更轻松地完成此操作,但即使这样,也没有一个单独的函数可以为您完成此操作。

票数 19
EN

Stack Overflow用户

发布于 2009-04-23 00:52:46

根本就没有。

你需要使用像strstr和strcat或strcpy这样的东西来编写你自己的代码。

票数 13
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/779875

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档