It doesn't seem clear to me what algorithm you are trying to follow, it all looks fishy to me. What's probably the simplest approach is:

  • search for first occurrence of the "needle" (searched-for substring)
  • copy the part before the first occurrence to the result buffer
  • append the replacement string to the result buffer
  • increment the p pointer so it points just after the needle
  • GOTO 10
void str_replace(char *target, const char *needle, const char *replacement)
{
    char buffer[1024] = { 0 };
    char *insert_point = &buffer[0];
    const char *tmp = target;
    size_t needle_len = strlen(needle);
    size_t repl_len = strlen(replacement);

    while (1) {
        const char *p = strstr(tmp, needle);

        // walked past last occurrence of needle; copy remaining part
        if (p == NULL) {
            strcpy(insert_point, tmp);
            break;
        }

        // copy part before needle
        memcpy(insert_point, tmp, p - tmp);
        insert_point += p - tmp;

        // copy replacement string
        memcpy(insert_point, replacement, repl_len);
        insert_point += repl_len;

        // adjust pointers, move on
        tmp = p + needle_len;
    }

    // write altered string back to target
    strcpy(target, buffer);
}

Warning: You also have to be careful about how you call your function. If the replacement string is larger than the needle, your modified string will be longer than the original one, so you have to make sure your original buffer is long enough to contain the modified string. E.g.:

char s[1024] = "marie has apples has";                         
str_replace(s, "has", "blabla");
Answer from The Paramagnetic Croissant on Stack Overflow
๐ŸŒ
Codeforwin
codeforwin.org โ€บ home โ€บ c program to replace all occurrences of a character in a string
C program to replace all occurrences of a character in a string - Codeforwin
July 20, 2025 - Run a loop from start of the string to end. The loop structure should look like while(str[i] != โ€˜\0โ€™). Inside the loop, replace current character of string with new character if it matches with old character.
๐ŸŒ
Tutorial Gateway
tutorialgateway.org โ€บ c-program-to-replace-all-occurrence-of-a-character-in-a-string
C Program to Replace All Occurrence of a Character in a String
January 26, 2025 - printf("\n The Final String after Replacing All Occurrences of '%c' with '%c' = %s ", ch, Newch, str); This program to replace all character occurrences is the same as above.
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ article โ€บ c-program-to-replace-all-occurrence-of-a-character-in-a-string
C program to replace all occurrence of a character in a string
March 15, 2026 - This method replaces every occurrence of a character in the string โˆ’ ยท #include <stdio.h> #include <string.h> int main() { char string[100], ch1, ch2; int i; printf("Enter a string: "); fgets(string, sizeof(string), stdin); string[strcspn(string, "<br>")] = '\0'; /* Remove newline */ printf("Enter character to search: "); scanf("%c", &ch1); getchar(); /* Clear buffer */ printf("Enter replacement character: "); scanf("%c", &ch2); for(i = 0; string[i] != '\0'; i++) { if(string[i] == ch1) { string[i] = ch2; } } printf("String after replacing '%c' with '%c': %s<br>", ch1, ch2, string); return 0; }
Top answer
1 of 5
19

It doesn't seem clear to me what algorithm you are trying to follow, it all looks fishy to me. What's probably the simplest approach is:

  • search for first occurrence of the "needle" (searched-for substring)
  • copy the part before the first occurrence to the result buffer
  • append the replacement string to the result buffer
  • increment the p pointer so it points just after the needle
  • GOTO 10
void str_replace(char *target, const char *needle, const char *replacement)
{
    char buffer[1024] = { 0 };
    char *insert_point = &buffer[0];
    const char *tmp = target;
    size_t needle_len = strlen(needle);
    size_t repl_len = strlen(replacement);

    while (1) {
        const char *p = strstr(tmp, needle);

        // walked past last occurrence of needle; copy remaining part
        if (p == NULL) {
            strcpy(insert_point, tmp);
            break;
        }

        // copy part before needle
        memcpy(insert_point, tmp, p - tmp);
        insert_point += p - tmp;

        // copy replacement string
        memcpy(insert_point, replacement, repl_len);
        insert_point += repl_len;

        // adjust pointers, move on
        tmp = p + needle_len;
    }

    // write altered string back to target
    strcpy(target, buffer);
}

Warning: You also have to be careful about how you call your function. If the replacement string is larger than the needle, your modified string will be longer than the original one, so you have to make sure your original buffer is long enough to contain the modified string. E.g.:

char s[1024] = "marie has apples has";                         
str_replace(s, "has", "blabla");
2 of 5
4

For starters:

This line

strncpy(buffer, string, p-string);

not necessarily appends a 0-terminator to what had been copied to buffer.

The following line

strcat(buffer, replace);

however relies on buffer being 0-terminated.

As buffer had not been initialised and though the 0-terminator most likely misses the latter line may very well read beyond buffer's memory and with this invoke the infamous Undefined Behaviour.

๐ŸŒ
CodezClub
codezclub.com โ€บ category: c programming โ€บ category: string programs โ€บ c program to replace all occurrences of character in string
C program to Replace all occurrences of character in string - CodezClub
November 10, 2016 - Any string ends with a terminating null character โ€˜\0โ€™. An array definition in such a way should include null character โ€˜\0โ€™ as the last element. Here is source code of the C program to Replace all occurrences of character in string. The C program is successfully compiled and run(on Codeblocks) on a Windows system.
๐ŸŒ
Learn Java
javatutoring.com โ€บ c-program-replace-occurrences-of-a-character-with-string
C Program Replace All Occurrences Of A Character With Another In String
February 25, 2026 - 3) Read the character by which we replace all occurrences of the element, store in the variable c2. 4) The for loop iterates through the string until the last character of the string becomes to null.
๐ŸŒ
YouTube
youtube.com โ€บ watch
Replace a character in a string with another character | C Programming Example - YouTube
An example of a function to replace all occurrences of a character in a string with another character using C. Source code: https://github.com/portfoliocour...
Published ย  July 6, 2021
Find elsewhere
๐ŸŒ
Tutorialride
tutorialride.com โ€บ c-strings-program โ€บ replace-a-character-in-string-c-program.htm
Replace a character in string - C Program
C Program to replace all occurrences of character 'a' with '*' symbol. Online C String programs for computer science and information technology students pursuing BE, BTech, MCA, MTech, MCS, MSc, BCA, BSc. Find code solutions to questions for lab practicals and assignments.
Top answer
1 of 2
5

The interface

  1. There are a number of useful things to return. Let's list them in order of which is least surprising:

    • The pointer to the start of the destination. This follows the standard library, but is least useful.
    • The pointer to the end of the destination. This follows an alternative convention embodies in the stpcpy() function and similar added to POSIX in 2008.
    • Number of characters produced / to produce. Generally only used if the sink can accept any number of characters, or the destinations size is also passed. countOccurrences() seems your flawed attempt to begin implementing the alternative approach to sizing the buffer.
    • Return a count of replacements done. Degenerates to boolean if maximum number of replacements is 1.
    • Try to combine bool (not count) with one of the other options. strstr() does it, arguable returning a pointer to the terminator might have been better.

    None of those options reflects your choice.

  2. Provide some way to properly size the destination buffer. As a bonus, replaceNAndAllocate() becomes fairly trivial.

The algorithm

  1. replaceN()'s use of replace() results in a standard Shlemiel The Painter-algorithm. It should be linear, but ends up quadratic.

  2. countOccurrences() can fail if some proper suffix (neither empty nor the full string) is a prefix of the needle, specifically if the resultant string is found. Skip over the full match found, not the first character.

Implementation

  1. Yes, strncpy() (which is not actually a string-function) will behave identically to memcpy() if the first n - 1 bytes are non-null. It is still inefficient and false advertisement though.

  2. &pointer[offset_calculation] might not be longer than pointer + offset_calculation, but it is a bit less idiomatic. You decide whether it should be changed.

  3. replaceN() should be the one to implement directly, replace() being a convenience-function. The overhead is trivial for the latter, and fixes the current problem with its runtime.

  4. Most of the time, you use pointer directly, but sometimes you use pointer != NULL. Fix the inconsistency, preferably in favor of the former, which is more idiomatic and shorter.

  5. countOccurrences() and allocateBuffer() seem to be internal helpers. Mark them static so they are not exported.

  6. Your test-program fails to free the buffer replaceAllAndAllocate() allocates.

2 of 2
2

First impression is pretty good - care taken with exception conditions and thought to the interface.

Headers: I find it helpful to have a consistent order for headers, to quickly see if the header I need is already included. For this, I group the Standard Library headers in alphabetical order. You might find that helpful too.

char *ptr = strstr(src, orig); // First match

I'd write const *ptr there, to avoid accidents.

strncpy(dest, src, offset); // Copy everything before match

Probably memcpy is more appropriate here, given we know that src doesn't end before src + offset.

strcpy(&dest[offset], new); // Copy replacement
strcpy(&dest[offset + strlen(new)], &src[offset + origlen]); // Copy rest

It's strange to index an array, only to extract a pointer. I'd write those as:

strcpy(dest + offset, new); // Copy replacement
strcpy(dest + offset + strlen(new), src + offset + origlen); // Copy rest

Arguably, we could measure strlen(new) first, then use memcpy for the first of those.

If countOccurrences() and allocateBuffer() aren't intended to be part of the public interface, declare them with internal linkage (static).

The test program is an optimist. If you've taken the care to safely return a null pointer from the function, the caller ought to have the decency to set a good example by testing the value rather than blindly passing it on!

๐ŸŒ
YouTube
youtube.com โ€บ shorts โ€บ Inltl8m7HV0
How to replace all occurrences of a character in string c++ - YouTube
AboutPressCopyrightContact usCreatorsAdvertiseDevelopersTermsPrivacyPolicy & SafetyHow YouTube worksTest new features ยท ยฉ 2026 Google LLC
Published ย  December 6, 2022
๐ŸŒ
Quora
quora.com โ€บ How-do-I-change-all-occurrences-of-a-character-in-a-string-in-c
How to change all occurrences of a character in a string in c++ - Quora
Answer (1 of 5): * Characters (chars) are just 8-bit signed integers. * You can just reassign them to any integer value withing the signed 8-bit range. ( -128 to 127, or [code ]0xFF[/code] to [code ]0xEF[/code]) . * The compiler will substitute the integer value for any single-quoted keyboard ...
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ modify-string-by-replacing-all-occurrences-of-given-characters-by-specified-replacing-characters
Modify string by replacing all occurrences of given characters by specified replacing characters
July 28, 2023 - Step 6 ? Iterate through the input string, get the respective character from the ?final' array for the current character, and append it to the ?result' string. Step 7 ? return the ?result' string. #include <bits/stdc++.h> using namespace std; // Function to replace the characters in the string string replaceChars(string str, vector<vector<char>> pairs){ // getting the size of the string and the vector int N = str.size(), M = pairs.size(); // Declare two arrays of size 26 char initial[26]; char final[26]; // Check all existing characters in the string for (int Y = 0; Y < N; Y++){ initial[str[Y]
๐ŸŒ
Quora
quora.com โ€บ How-do-I-replace-all-occurrences-of-a-string-in-C
How to replace all occurrences of a string in C++ - Quora
Quora is a place to gain and share knowledge. It's a platform to ask questions and connect with people who contribute unique insights and quality answers.
Top answer
1 of 16
118

The optimizer should eliminate most of the local variables. The tmp pointer is there to make sure strcpy doesn't have to walk the string to find the null. tmp points to the end of result after each call. (See Shlemiel the painter's algorithm for why strcpy can be annoying.)

// 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;
}
2 of 16
21

This is not provided in the standard C library because, given only a char* you can't increase the memory allocated to the string if the replacement string is longer than the string being replaced.

You can do this using std::string more easily, but even there, no single function will do it for you.

๐ŸŒ
Microsoft Learn
learn.microsoft.com โ€บ en-us โ€บ dotnet โ€บ api โ€บ system.string.replace
String.Replace Method (System) | Microsoft Learn
March 16, 2023 - You can try changing directories. ... Some information relates to prerelease product that may be substantially modified before itโ€™s released. Microsoft makes no warranties, express or implied, with respect to the information provided here. Returns a new string in which all occurrences of a specified Unicode character or String in the current string are replaced with another specified Unicode character or String.
Top answer
1 of 16
1003

std::string doesn't contain such function but you could use stand-alone replace function from algorithm header.

#include <algorithm>
#include <string>

void some_func() {
  std::string s = "example string";
  std::replace( s.begin(), s.end(), 'x', 'y'); // replace all 'x' to 'y'
}
2 of 16
179

The question is centered on character replacement, but, as I found this page very useful (especially Konrad's remark), I'd like to share this more generalized implementation, which allows to deal with substrings as well:

std::string ReplaceAll(std::string str, const std::string& from, const std::string& to) {
    size_t start_pos = 0;
    while((start_pos = str.find(from, start_pos)) != std::string::npos) {
        str.replace(start_pos, from.length(), to);
        start_pos += to.length(); // Handles case where 'to' is a substring of 'from'
    }
    return str;
}

Usage:

std::cout << ReplaceAll(string("Number Of Beans"), std::string(" "), std::string("_")) << std::endl;
std::cout << ReplaceAll(string("ghghjghugtghty"), std::string("gh"), std::string("X")) << std::endl;
std::cout << ReplaceAll(string("ghghjghugtghty"), std::string("gh"), std::string("h")) << std::endl;

Outputs:

Number_Of_Beans

XXjXugtXty

hhjhugthty


EDIT:

The above can be implemented in a more suitable way, in case performance is of your concern, by returning nothing (void) and performing the changes "in-place"; that is, by directly modifying the string argument str, passed by reference instead of by value. This would avoid an extra costly copy of the original string by overwriting it.

Code :

static inline void ReplaceAll2(std::string &str, const std::string& from, const std::string& to)
{
    // Same inner code...
    // No return statement
}

Hope this will be helpful for some others...

๐ŸŒ
Cplusplus
cplusplus.com โ€บ reference โ€บ string โ€บ string โ€บ replace
std::string::replace
Copies the null-terminated character sequence (C-string) pointed by s. ... Copies the first n characters from the array of characters pointed by s. ... Replaces the portion of the string by n consecutive copies of character c.