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

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

Required knowledge

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

Logic to replace last occurrence of a character

Below is the step by step descriptive logic to replace last 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. Initialize another variable to store last index of matched character, say lastIndex = -1. Initially I have assumed that the character does not exists in the string. Hence, initialized lastIndex -1.
  4. Run a loop from start of string str to end. The loop structure should loop like while(str[i]!='\0')
  5. Inside the loop check if(str[i] == oldChar), then update the lastIndex with i.
  6. Finally, after loop replace the last occurrence of character if exists with new character. Say if(lastIndex != -1) then str[lastIndex] = newChar.

Program to replace last occurrence of a character




 
/**
 * C program to replace last occurrence of a character with another in a string
 */

#include <stdio.h>
#define MAX_SIZE 100 // Maximum string size

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

    replaceLast(str, oldChar, newChar);

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

    return 0;
}


/**
 * Replace last occurrence of a character with 
 * another in given string.
 */
void replaceLast(char * str, char oldChar, char newChar)
{
    int i, lastIndex;

    lastIndex = -1;
    i = 0;

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

        i++;
    }

    if(lastIndex != -1)
    {
        str[lastIndex] = newChar;
    }
}



Output:

Enter any string: c programcading
Enter character to replace: a
Enter character to replace 'a' with: o
String before replacing:
c programcading
String after replacing 'a' with 'o':
c programcoding
Process returned 0 (0x0) execution time : 32.495 s



Instagram