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

Answer from Superlokkus on Stack Overflow
Discussions

Replacing strings in an array in C - Stack Overflow
This will also overwrite other parts the array if the length of the string you replace with is different. If you want replace all instances (of "john" with "jack" for example), use a loop over strstr(). ... Is this a homework or something? I think C is nearly the worst choice of a language for this kind of task. ... You don't want to modify the pointer, you want to modify what the pointer points to. Also the ret points to a character... More on stackoverflow.com
๐ŸŒ stackoverflow.com
May 25, 2015
How to replace a specific but changing series of characters in an array in C? - Stack Overflow
I am working on 2 different programs, but have the same problem for both. I have a char array (that doesn't hold meaningful text) that I use for drawing things on the screen. The first one is for a... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Replacing a string in char array - C++ Forum
Find the string which has to be replaced in the main string with strstr function. Then save the characters after the string you need to replace to another string (tail). Copy the string that has to replace the older one and finally add the tail to the end of the main string. More on cplusplus.com
๐ŸŒ cplusplus.com
January 5, 2015
Replacing a character in a string (char array) with multiple characters in C - Stack Overflow
I need to create a block of code which searches through a character array, and replaces all instances of '2' with 'Ba'. This is quite simple, except for the fact that now the resulting string will be larger than the original, so I need to account for this somehow, and I don't remember how to ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Top answer
1 of 4
1
#include <stdio.h>

int main(void) {
    char* words[3] = {"cat", "dog", "bird"};
    
    printf("The Initial List\n");
    for(int i=0; i<3; ++i)
    {
        printf("%d : %s\n", i, words[i]);
    }
    
    // Replace the middle entry
    char* replacement = "mouse";
    words[1] = replacement;
    
    printf("The Final List\n");
    for(int i=0; i<3; ++i)
    {
        printf("%d : %s\n", i, words[i]);
    }

    return 0;
}

Output:

Success #stdin #stdout 0.01s 5464KB
The Initial List
0 : cat
1 : dog
2 : bird
The Final List
0 : cat
1 : mouse
2 : bird
2 of 4
1

This code:

char * words[3];
words[0] = "cat";
words[1] = "dog";
words[2] = "bird";

...is roughly equivalent to:

// Internal memory you can't see:
char _string1[] = {'c','a','t','\0'} // Address 0x001234
char _string2[] = {'d','o','g','\0'} // Address 0x001238
char _string3[] = {'b','i','r','d','\0'} // Address 0x001242

// Your program memory:
char * words[3];
words[0] = (char *)0x001234;
words[1] = (char *)0x001238;
words[2] = (char *)0x001242;

The important thing is char * s is not the same as char s[], so trying to copy "mouse" over 0x001238 doesn't do what you want.

Given char word[] = "mouse";, word does have an address so you can assign that as in words[1] = word; and that will work. Of course if you change word[0] = 'h'; to make it "house" then words[1] will also be "house".

If that's not a problem for you, then it's fine, otherwise you'll need words to be an array of characters rather than an array of pointers, and make sure there are enough characters to hold all the words you want. Since most words will be shorter than that, a lot of characters will be unused, but that's not normally a big problem.

Otherwise you will have to use malloc(), free(), strdup(), and so on to manage the memory and that gets complicated, so best avoid that unless you really need to.

๐ŸŒ
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.
๐ŸŒ
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.
๐ŸŒ
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.
Find elsewhere
๐ŸŒ
Cplusplus
cplusplus.com โ€บ forum โ€บ beginner โ€บ 152695
Replacing a string in char array - C++ Forum
January 5, 2015 - Find the string which has to be replaced in the main string with strstr function. Then save the characters after the string you need to replace to another string (tail). Copy the string that has to replace the older one and finally add the tail to the end of the main string.
๐ŸŒ
Quora
quora.com โ€บ How-do-I-replace-a-character-in-a-string-with-3-characters-using-C-programming-language
How to replace a character in a string with 3 characters using C programming language - Quora
Answer (1 of 11): All kinds of pretty good answers here, but a bit shocking that no one mentioned the perils of doing that without knowing about the storage used for the string. Many times, character arrays are allocated with fixed sizes, sometimes matching the exact length of the string it conta...
Top answer
1 of 1
1

You need to replace only when you find the full substring.

There are useful standard functions :

  • strstr allows to find a substring in a string
  • memcpy can be used to replace the old substring by the new one

A proposal :

#include <stdio.h>
#include <string.h>

int main(int argc, char ** argv)
{
  if (argc != 4)
    printf("usage : %s <str> <old> <new>\n", *argv);
  else {
    char * old = argv[2];
    char * new = argv[3];
    size_t len = strlen(old);

    if (len != strlen(new))
      fprintf(stderr, "'%s' and '%s' do not have the same length\n", old, new);
    else {
      char * str = argv[1];
      char * p = str;

      printf("'%s' -> ", str);

      /* the loop doing the replacements */
      while ((p = strstr(p, old)) != NULL) {
        memcpy(p, new, len);
        p += len;
      }

      printf("'%s'\n", str);
    }
  }

  return 0;
}

Compilation and execution :

pi@raspberrypi:/tmp $ gcc -pedantic -Wextra -Wall r.c
pi@raspberrypi:/tmp $ ./a.out
usage : ./a.out <str> <old> <new>
pi@raspberrypi:/tmp $ ./a.out xyzdefxyzghixy xyz abc
'xyzdefxyzghixy' -> 'abcdefabcghixy'

Edit

NB: please Note that I wish to only use stdio.h

Can be :

#include <stdio.h>

int main(int argc, char ** argv)
{
  if (argc != 4)
    printf("usage : %s <str> <old> <new>\n", *argv);
  else {
    char * old = argv[2];
    char * new = argv[3];
    char * str = argv[1];

    /* check old and new have the same length */
    char * pold, * pnew;

    for (pold = old, pnew = new; *pold && *pnew; ++pold, ++pnew)
      ;

    if (*pold || *pnew)
      fprintf(stderr, "'%s' and '%s' do not have the same length\n", old, new);
    else {
      printf("'%s' -> ", str);

      char * pstr = str;

      /* the loop doing the replacements */
      while (*pstr) {
        /* check if substring */
        char * pold = old;
        char * psubstr = pstr;

        while (*pold && (*pold == *psubstr)) {
          pold += 1;
          psubstr += 1;
        }

        if (*pold == 0) {
          /* substring, replacement */
          pnew = new;

          while (*pnew)
            *pstr++ = *pnew++;
        }
        else
          pstr += 1;
      }

      printf("'%s'\n", str);
    }
  }

  return 0;
}

As you can see this is a bad choice, it is very easy to understand what the previous version does, this is not the case with that version

๐ŸŒ
Reddit
reddit.com โ€บ r/learnprogramming โ€บ [c] replacing characters in a string
r/learnprogramming on Reddit: [C] Replacing characters in a string
March 22, 2021 -

Got the following exercise:

Given a string, use a function to replace each character with the following character in the alphabet. That is, if the string is ABC, the new string would have to be BCD. If Z (or z) is in the string, it should be replaced with A (or a). The function must have the following scope:

void shift_string (char* str);

I got the replacement for the next letter with no issues. However, my code is not replacing "z" with "a". Here's my code

#include <stdio.h>
#include <stdlib.h>
#define MAX 255

void shift_string (char* str)
{
	int i;
	char c1 = 'Z';
	char c2 = 'z';
	char new_c1 = 'A';
	char new_c2 = 'a';

	for  (i = 0; str[i] != '\0'; i++)
	{
		str[i] = (int)str[i] +  1;
		if (str[i] == c1)
			str[i] = new_c1;
		else if (str[i] == c2)
			str[i] = new_c2;
	}
}

And the main function:

int main (void)
{
	char *str;
	str = (char*) malloc(MAX * sizeof(int));
	printf("Enter a string (max. %d characters): ", MAX);
	scanf(" %255[^\n]", str);
	int size = sizeof(str) / sizeof( str[0]);
	printf("\nString: %s", str);
	printf("\n");
	shift_string (str);
	printf("\n");
	printf("New string: %s", str);
	printf("\n\n");

	return 0;
}

However, if I input something like ZXCVB, I get the following output:

[YDWC

What am I doing wrong here? Why isn't the if statement working?

๐ŸŒ
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; }
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ dsa โ€บ replace-character-c1-c2-c2-c1-string-s
Replace a character c1 with c2 and c2 with c1 in a string S - GeeksforGeeks
// C program to replace c1 with c2 // and c2 with c1 #include <stdio.h> #include <stdlib.h> #include <string.h> char * replace(char s[40], char c1, char c2) { int l = strlen(s); // loop to traverse in the string for (int i = 0; i < l; i++) { ...
Published ย  February 17, 2023
๐ŸŒ
Quora
quora.com โ€บ How-do-I-replace-a-character-in-one-string-to-another-string-using-the-C-programming-language
How to replace a character in one string to another string using the C programming language - Quora
Answer (1 of 2): For character to string replacement you have basically three ways. * If the buffer is large enough use memmove enough to insert needed spaces, starting from rightmost. * Buffer too small? realloc, the same as above * Allocate a new buffer of proper size, then use strchr to fi...
๐ŸŒ
Arduino Forum
forum.arduino.cc โ€บ projects โ€บ programming
Replace and remove char arrays - Programming - Arduino Forum
October 15, 2017 - The replace() function allows you to replace all instances of a given character with another character. You can also use replace to replace substrings of a string with a different substring.
Top answer
1 of 2
3

Replace character with character

This code will replace every occurrence of the character 'n' with the character '1'.

#include <stdio.h>

int main(void)
{
    char str[15];
    printf("Input: ");
    scanf("%14s", str); // prevent buffer overflow

    for (int i = 0; str[i]; ++i) { // iterate over str
        if (str[i] == 'n')
            str[i] = '1';
    }

    printf("Modified: %s\n", str);

    return 0;
}

Replace character with string

This code will replace every occurrence of the character 'n' with the string "1+k" using the function strcat. The modified string is saved to char mod[].

#include <stdio.h>
#include <string.h>

#include <stdio.h>

int main(void)
{
    char str[15];
    printf("Input: ");
    scanf("%14s", str); // prevent buffer overflow

    char mod[] = "";

    for (int i = 0; str[i]; ++i) { // iterate over str
        if (str[i] == 'n') {
            char *repl = "1+k";
            strcat(mod, repl); // add "1+k" to mod
        } else {
            strncat(mod, &str[i], 1); // add str[i] to mod
        }
    }

    printf("Modified: %s\n", mod);

    return 0;
}
2 of 2
1

Such a trivial question deserves a non trivial answer

Note that this approach with branching, demonstrated by @Andy Sukowski-Bang, is - when compiled with -O3 - roughly 6.5x time slower than my approach, illustratating the efficiency of bitwise operations over branching instructions (not to mention Meltdown and Spectre vulnerabilities and its on branching if mitigations are enabled).

The following program will convert every occurence of the letter from to the designated letter.

It is able to replace all characters from 'A' to 'z' to '8' in a string of 8,286,208 bytes in only 0.07s:

#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <time.h>

// gcc -O3 replace.c && ./a.out

void replace(char *s, char from, char to, long n) {
    char eq;
    while (n--) {
        eq = !(*s ^ from);
        *s = !eq * *s + eq * to;
        s++;
    }
}

void replace_branching(char *s, char from, char to, long n) {
    while (n--) {
        if (*s == from)
            *s = to;
        s++;
    }
}

void read_file_to_buffer(FILE *f, long length) {
    char buffer[length + 1];
    fseek(f, 0, SEEK_SET);
    void (*fptr[2]) (char *s, char from, char to, long n) = {replace_branching, replace};

    if (fread (buffer, 1, length, f) ) {
        buffer[length] = '\0';
        fclose (f);

        char subbuff[33];
        subbuff[32] = '\0';
        char from = 'A';
        char to = '8';
        clock_t start, end;
        double cpu_time_used[2];
        for (int j = 0; j < 2; j++){
            start = clock();
            for (int i = 0; i < 0x20 + 26; i++) {
                fptrj;
                //memcpy( subbuff, &buffer[0], 32 );
                //printf("Modified: %s\n", subbuff);
            }
            end = clock();
            cpu_time_used[j] = ((double) (end - start)) / CLOCKS_PER_SEC;
            printf("Time: %fs\n", cpu_time_used[j]);
        }
        printf("Without branching it is %fx faster\n", cpu_time_used[0] / cpu_time_used[1]);
    }
}

int main(void)
{
    FILE * f;
    long length;
    if ((f = fopen ("test.txt", "rb"))) // NB: test.txt is a file of 8,286,208 bytes
    {
      fseek (f, 0, SEEK_END);
      read_file_to_buffer(f, ftell(f));
    }
    return 0;
}

/*
    Time: 0.475005s
    Time: 0.070859s
    Without branching it is 6.703524x faster
*/

Some explanations

eq = !(*s ^ from); // eq will equal 0 if letters are same, else it will equal 1
*s = !eq * *s + eq * to; // we assign to the pointer its same old value with !eq if the character 'from' was absent, else we will assign the character 'to'.

PS: No malloc were used, I used VLA and it is bad, very bad, don't do this at home!

๐ŸŒ
Cplusplus
cplusplus.com โ€บ forum โ€บ beginner โ€บ 97492
Changing characters in char array - C++ Forum
You defined variable str as a pointer to string literal char * str="Palko vybehni na scenu, bez teba to nema cenu"; The correct its declaration shall look as const char * str="Palko vybehni na scenu, bez teba to nema cenu"; That to provide the possibility of changing the source string change the definition to char str[] ="Palko vybehni na scenu, bez teba to nema cenu";