22

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?

2
  • Not really - you either have to write your own or look for a suitable third-party library. Commented Sep 10, 2015 at 8:15
  • 1. No, 2. No You'll have to write your own or migrate to C++ Commented Sep 10, 2015 at 8:19

2 Answers 2

29

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

Sign up to request clarification or add additional context in comments.

3 Comments

Better to start searching from current_pos+1 in the second strchr, to avoid O(n^2) running time.
@interjay You're right, I thought I had. Damn Shlemiel the painter's algorith :-)
Or, much more succinctly: for (char* p = current_pos; (current_pos = strchr(str, find)) != NULL; *current_pos = replace);
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.