Problem 38

author
By Supreme2023-03-15
Problem Statement :
Write a program to replace a character in given string.
Code:

#include <stdio.h>
#include <string.h>

int main(){

//38. Write a program to replace a character in given string.

char str[100],ch,ch2;
int i,signal=0;

printf("\tReplace_Character");
printf("\n=========================================\n\n");

printf("Enter Your String : ");
gets(str);

// printf("\nYour String Is : ");
// puts(str);

printf("\nEnter The Character To Replace : ");
scanf(" %c",&ch);

printf("\nEnter The New Character To Replace %c : ",ch);
scanf(" %c",&ch2);

printf("\n-----------------------------------------\n");

for(i=0;str[i] != '\0';i++){
if(ch == str[i]){
str[i] = ch2;
signal = 1;
}
}

if(signal == 0){
printf("\n\n%c Is Not Found In Given String",ch);
}

printf("\nNew String Is : ");
puts(str);

printf("\n-----------------------------------------\n");

return 0;
}

Description :
  • This is a C program to replace a character in a given string.
  • The program includes the necessary header files for standard input-output and string manipulation functions.
  • The main function is defined.
  • The string 'str' is declared with a size of 100 characters, and the characters 'ch' and 'ch2' are declared.
  • The program displays a message asking the user to enter a string.
  • The user inputs a string using the gets() function.
  • The program asks the user to enter the character to be replaced.
  • The user inputs the character using the scanf() function.
  • The program asks the user to enter the new character.
  • The user inputs the new character using the scanf() function.
  • A loop is used to iterate through the string 'str' until the end of the string ('\0') is reached.
  • If the character 'ch' is found in the string, it is replaced with the new character 'ch2', and the 'signal' variable is set to 1.
  • If the 'signal' variable remains 0, it means that the character 'ch' was not found in the string.
  • The program displays the modified string using the puts() function.
  • The main function returns 0, indicating successful execution of the program.
Output Image:
Output-image

© Copyright 2022. All right reserved, GTU Coder.