Write a C program to replace first occurrence of a character with another character in a string. How to replace first occurrence of a character with another character in a string using loop in C programming. Logic to replace first occurrence of a character in given string.
Example
Input
Input string: I love programming. Input character to replace: . Input character to replace with: !
Output
String after replacing '.' with '!': I love programming!
Required knowledge
Basic C programming, Loop, String, Function
Must know – Program to find first occurrence of a character in string
Logic to replace first occurrence of a character
Below is the step by step descriptive logic to replace first 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.
- 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, swap old character with new character i.e. str[i] = newChar and terminate the loop.
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 string size
/* Function declaration */
void replaceFirst(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();
// Used to skip extra ENTER character
getchar();
printf("Enter character to replace '%c' with: ", oldChar);
newChar = getchar();
printf("\nString before replacing: %s\n", str);
replaceFirst(str, oldChar, newChar);
printf("String after replacing first '%c' with '%c' : %s", oldChar, newChar, str);
return 0;
}
/**
* Replace first occurrence of a character with
* another in given string.
*/
void replaceFirst(char * str, char oldChar, char newChar)
{
int i=0;
/* Run till end of string */
while(str[i] != '\0')
{
/* If an occurrence of character is found */
if(str[i] == oldChar)
{
str[i] = newChar;
break;
}
i++;
}
}
Read more – Program to replace last occurrence of a character in a string
Output
Enter any string: I love Codeforwin. Enter character to replace: I Enter character to replace 'I' with: ! String before replacing: I love Codeforwin. String after replacing first 'I' with '!' : ! love Codeforwin.
Happy coding 😉
Recommended posts
- String programming exercises index.
- C program to replace all occurrences of a character with another 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.
- C program to remove first occurrence of a word from given string.
- C program to remove last occurrence of a word from given string.
- C program to remove all occurrence of a word from given string.