Standard function to replace character or substrin

2019-06-25 08:44发布

问题:

This question already has an answer here:

  • What is the function to replace string in C? 18 answers

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?

回答1:

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



回答2:

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



标签: c string replace