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.

Required knowledge

Basic C programming, C if-else, C for loop, Array, functions, Strings

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++;
    }
}



Output:

Enter any string: I love p programming
Enter character to replace: p
Enter character to replace 'p' with: c
String before replacing:
I love p programming
String after replacing 'p' with 'c' :
I love c crogramming
Process returned 0 (0x0) execution time : 15.858 s



Instagram