C Programming Code Examples C > Strings Code Examples C program to replace last occurrence of a character in a string 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. Logic to replace last occurrence of a character Input string from user, store it in some variable say str. Input character to replace and character new character from user, store it in some variable say oldChar and newChar. 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. Run a loop from start of string str to end. The loop structure should loop like while(str[j]!='\0') Inside the loop check if(str[j] == oldChar), then update the lastIndex with j. Finally, after loop replace the last occurrence of character if exists with new character. Say if(lastIndex != -1) then str[lastIndex] = newChar. /* C program to replace last occurrence of a character with another in a string */ #include <stdio.h> #define maxsize 100 // Maximum string size /* Function declaration */ void replaceLast(char * str, char oldChar, char newChar); int main() { char str[maxsize], 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 j, lastIndex; lastIndex = -1; j = 0; /* Run till end of string */ while(str[j] != '\0') { /* If an occurrence of character is found */ if(str[j] == oldChar) { lastIndex = j; } j++; } if(lastIndex != -1) { str[lastIndex] = newChar; } }