c - 什么功能是用C语言替换字符串中的子字符串?

标签 c string replace

给定一个 ( char *) 字符串,我想找到所有出现的子字符串并将它们替换为备用字符串。我在 <string.h> 中没有看到任何实现此目的的简单函数.

最佳答案

优化器应该消除大部分局部变量。 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;
}

关于c - 什么功能是用C语言替换字符串中的子字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/779875/

相关文章:

SQL left 2 或 Convert(varchar(2) ,'Chgffgjjx' ) 哪个更快

replace - SPARQL 1.1 : how to use the replace function?

c++ - 一元增量运算符的原子行为

python - 在Python中迭代地对左括号和右括号之间的值进行排序

sql - 如何从 C 程序执行 sql 语句?

string - 液体字符串中的转义字符

mysql - 当存在特殊字符时,使用 REPLACE() 按字母数字顺序对 mySQL SELECT 进行 ORDER BY

java - 当替换文本与搜索文本重叠时替换 Java 中的多个子字符串

c - 如果 char c = 0x80,为什么 printf ("%d\n", c << 1) 输出 -256?

c - 如何比较无符号和有符号长变量?