String Exercises
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.
- 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
/** * 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; } }