C program to replace first occurrence of a character in a string

Write a C program to replace first occurrence of a character with another character in a string. How to replace first occurrence of a character with another character in a string using loop in C programming. Logic to replace first occurrence of a character in given string.

Example

Input

Input string: I love programming.
Input character to replace: .
Input character to replace with: !

Output

String after replacing '.' with '!': I love programming!

Required knowledge

Basic C programming, Loop, String, Function

Must know - Program to find first occurrence of a character in string

Logic to replace first occurrence of a character

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

  1. Input string from user, store it in some variable say str.
  2. Input character to replace and character new character from user, store it in some variable say oldChar and newChar.
  3. Run a loop from start of string str to end. The loop structure should loop like while(str[i]!='\0')
  4. Inside the loop check if(str[i] == oldChar). Then, swap old character with new character i.e. str[i] = newChar and terminate the loop.

Program to replace first occurrence of a character

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

/* Function declaration */
void replaceFirst(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();

    // Used to skip extra ENTER character
    getchar();

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


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

    replaceFirst(str, oldChar, newChar);

    printf("String after replacing first '%c' with '%c' : %s", oldChar, newChar, str);

    return 0;
}


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

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

        i++;
    }
}

Read more - Program to replace last occurrence of a character in a string

Output

Enter any string: I love Codeforwin.
Enter character to replace: I
Enter character to replace 'I' with: !

String before replacing: I love Codeforwin.
String after replacing first 'I' with '!' : ! 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>