Example:
Input string: I love programming.
Input character to replace: .
Input character to replace with: !
Output after replace: I love programming!
Required knowledge
Basic C programming, Loop, String, FunctionLogic to replace first occurrence of a character
To replace the first occurrence of a character with another character the one out of two things we need to do is find the first occurrence of the character to be replaced. After locating the index of character to be replaced change its value to new character.Program to replace first occurrence of a character
/** * C program to replace first occurrence of a character with another in a string */ #include <stdio.h> #define MAX_SIZE 100 //Maximum size of the string /* Function declaration */ void replaceFirst(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); replaceFirst(string, toReplace, replaceWith); printf("String after replacing: %s\n", string); return 0; } /** * Replaces the first occurrence of a character * with another in given string. */ void replaceFirst(char * string, char toReplace, char replaceWith) { int i=0; /* Runs till the end of string */ while(string[i] != '\0') { /* If an occurrence of character is found */ if(string[i] == toReplace) { string[i] = replaceWith; break; } i++; } }
Output
Enter any string: I love programming.
Enter character to replace: .
Enter character to replace '.' with: !
String before replacing: I love programming.
String after replacing: I love programming!
Enter character to replace: .
Enter character to replace '.' with: !
String before replacing: I love programming.
String after replacing: I love programming!
Happy coding ;)
You may also like
- String programming exercises index.
- C program to replace last occurrence of a character in a string.
- C program to replace all occurrences of a character with another in a string.
- C program to compare two strings.
- C program to toggle case of each character in a string.
- C program to find reverse of a string.
- C program to check whether a string is palindrome or not.
- C program to search all occurrence of a character in a string.
- C program to find highest frequency character in a string.
- C program to find lowest frequency character in a string.
- C program to count frequency of each character in a string.
- C program to remove all occurrence of a character in a string.
- C program to remove all repeated character from a given string.