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.
Example
Input
Input string: Do you love programming. Input character to replace: . Input character to replace with: ?
Output
String after replacing last '.' with '?' : Do you love programming?
Required knowledge
Basic C programming, Loop, String, Function
Must know – Program to find last occurrence of a character in given string
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.
- 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[i]!=’\0′)
- Inside the loop check if(str[i] == oldChar), then update the lastIndex with i.
- 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
Read more – Program to replace all occurrences of a character
Output
Enter any string: Do you love programming. Enter character to replace: . Enter character to replace '.' with: ? String before replacing: Do you love programming. String after replacing '.' with '?' : Do you love programming?
Happy coding
Recommended posts
- String programming exercises index.
- C program to remove all occurrences of a character in a given string.
- C program to remove all repeated character in a string.
- C program to trim leading white space characters in a string.
- C program to trim trailing white space characters in a string.
- C program to trim leading and trailing white space characters in a string.
- C program to count total words in a string.