C program to replace all occurrences of a character in a string

Write a C program to replace all occurrence of a character with another in a string using function. How to replace all occurrences of a character with another in a string using functions in C programming. Logic to replace all occurrences of a character in given string.

Example

Input

Input string: I_love_learning_at_Codeforwin.
Input character to replace: _
Input character to replace with: -

Output

String after replacing '_' with '-': I-love-learning-at-Codeforwin

Required knowledge

Basic C programming, Loop, String, Function

Must know -

Logic to replace all occurrence of a character

Below is the step by step descriptive logic to replace all occurrence of a character in a given string.

  1. Input a string from user, store it in some variable say str.
  2. Input old character and new character which you want to replace. Store it in some variable say oldChar and newChar.
  3. Run a loop from start of the string to end. The loop structure should look like while(str[i] != '\0').
  4. Inside the loop, replace current character of string with new character if it matches with old character. Means, if(str[i] == oldChar) then str[i] = newChar.

Program to replace all occurrences of a character

/**
 * C program to replace all occurrence of a character with another in a string
 */
#include <stdio.h>
#define MAX_SIZE 100 // Maximum string size

/* Function declaration */
void replaceAll(char * str, char oldChar, char newChar);


int main()
{
    char str[MAX_SIZE], oldChar, newChar;

    printf("Enter any string: ");
    gets(str);

    printf("Enter character to replace: ");
    oldChar = getchar();

    // Dummy getchar() to eliminate extra ENTER character
    getchar();

    printf("Enter character to replace '%c' with: ", oldChar);
    newChar = getchar();


    printf("\nString before replacing: \n%s", str);

    replaceAll(str, oldChar, newChar);

    printf("\n\nString after replacing '%c' with '%c' : \n%s", oldChar, newChar, str);

    return 0;
}


/**
 * Replace all occurrence of a character in given string.
 */
void replaceAll(char * str, char oldChar, char newChar)
{
    int i = 0;

    /* Run till end of string */
    while(str[i] != '\0')
    {
        /* If occurrence of character is found */
        if(str[i] == oldChar)
        {
            str[i] = newChar;
        }

        i++;
    }
}

Read more - Program to replace last occurrence of a character

Output

Enter any string: I_love_Codeforwin.
Enter character to replace: _
Enter character to replace '_' with: -

String before replacing: 
I_love_Codeforwin.

String after replacing '_' with '-' : 
I-love-Codeforwin.

Happy coding 😉

Write your doubts or suggestion. I will try my best to help. You must escape source code before commenting. To format your source code paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>