Example:
Input string: Do you love programming.
Input character to replace: .
Input character to replace with: ?
Output after replace: Do you love programming?
Required knowledge
Basic C programming, Loop, String, FunctionLogic to replace last occurrence of a character
We have already seen how easily we can replace first occurrence of a character with another. Here also we will be using same concept we used in previous program. What we need to do is find the last occurrence of the character and change its value to the new value.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 size of the string /* Function declaration */ void replaceLast(char * string, char toReplace, char replaceWith); int main() { char string[MAX_SIZE], toReplace, replaceWith; printf("Enter any string: "); gets(string); printf("Enter character to replace: "); scanf(" %c", &toReplace); printf("Enter character to replace '%c' with: ", toReplace); scanf(" %c", &replaceWith); printf("\nString before replacing: %s\n", string); replaceLast(string, toReplace, replaceWith); printf("String after replacing: %s\n", string); return 0; } /** * Replaces the last occurrence of a character * with another in given string. */ void replaceLast(char * string, char toReplace, char replaceWith) { int i, index; index = -1; i = 0; /* Runs till the end of string */ while(string[i] != '\0') { /* If an occurrence of character is found */ if(string[i] == toReplace) { index = i; } i++; } if(index != -1) { string[index] = replaceWith; } }
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: Do you love programming?
Enter character to replace: .
Enter character to replace '.' with: ?
String before replacing: Do you love programming.
String after replacing: Do you love programming?
Happy coding ;)
You may also like
- String programming exercises index.
- C program to replace all occurrences of a character with another 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 find first occurrence of a character in a given string.
- C program to search all occurrence of a character in given string.
- C program to count occurrence of all characters in a given string.
- C program to count frequency of each character in a string.
- 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 count total words in a string.