21

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?

moooeeeep
  • 31,622
  • 22
  • 98
  • 187
MOHAMED
  • 41,599
  • 58
  • 163
  • 268

2 Answers2

26

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

pevik
  • 4,523
  • 3
  • 33
  • 44
Superlokkus
  • 4,731
  • 1
  • 25
  • 57
  • 3
    Better to start searching from `current_pos+1` in the second `strchr`, to avoid O(n^2) running time. – interjay Sep 10 '15 at 08:40
  • 1
    @interjay You're right, I thought I had. Damn Shlemiel the painter's algorith :-) – Superlokkus Sep 10 '15 at 08:43
  • 1
    Or, much more succinctly: `for (char* p = current_pos; (current_pos = strchr(str, find)) != NULL; *current_pos = replace);` – vladr Nov 08 '17 at 18:33
13

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

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252