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.

Required knowledge

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

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



Output:

Enter any string: G Rama
Enter character to replace: G
Enter character to replace 'G' with: C
String before replacing: G Rama
String after replacing first 'G' with 'C' : C Rama
Process returned 0 (0x0) execution time : 25.703 s



Instagram