Standard function to replace character or substrin

2019-06-25 08:40发布

This question already has an answer here:

I need a function from the standard library that replaces all occurrences of a character in a string by another character.

I also need a function from the standard library that replaces all occurrences of a substring in a string by another string.

Are there any such functions in the standard library?

标签: c string replace
2条回答
疯言疯语
2楼-- · 2019-06-25 08:56

There is no direct function to do that. You have to write something like this, using strchr:

char* replace_char(char* str, char find, char replace){
    char *current_pos = strchr(str,find);
    while (current_pos){
        *current_pos = replace;
        current_pos = strchr(current_pos,find);
    }
    return str;
}

For whole strings, I refer to this answered question

查看更多
smile是对你的礼貌
3楼-- · 2019-06-25 09:18

There are not such functions in the standard libraries.

You can easily roll your own using strchr for replacing one single char, or strstr to replace a substring (the latter will be slightly more complex).

int replacechar(char *str, char orig, char rep) {
    char *ix = str;
    int n = 0;
    while((ix = strchr(ix, orig)) != NULL) {
        *ix++ = rep;
        n++;
    }
    return n;
}

This one returns the number of chars replaced and is even immune to replacing a char by itself

查看更多
登录 后发表回答