Programming for Problem Solving

GTU Practical 38

38. Write a program to replace a character in the given string
#include<stdio.h>  ( this applies in the given code )

#include

int main() {
char str[100], oldChar, newChar;

printf(“Enter a string: “);
fgets(str, sizeof(str), stdin);

printf(“Enter the character to replace: “);
scanf(“%c”, &oldChar);
getchar();
printf(“Enter the new character: “);
scanf(“%c”, &newChar);

for(int i = 0; str[i] != ‘\0’; i++) {
if(str[i] == oldChar) {
str[i] = newChar;
}
}

printf(“Modified string: %s\n”, str);

return 0;
}

OUTPUT

Enter a string: kong
Enter the character to replace: o
Enter the new character: i
Modified string: king