A C Program to replace a character in a String Using Function – IGNOU MCA Assignment 2013

By | September 15, 2013

MASTER OF COMPUTER APPLICATIONS
Course Code : MCS-011
Course Title : Problem Solving and Programming
Assignment Number : MCA(1)/011/Assign/13
Assignment 2013 

 

A C program function strreplace(s, chr, repl_chr) which will replace each occurrences of character chr with the character repl_chr in the string s. The function returns the number of replacements. Place the source code of this function in a file named strreplace.c

 

#include<stdio.h>
void main()
{
    int COUNT;
    char CHR,REPL_CHR,S[50];
    int strreplace(char S[],char CHR,char REPL_CHR);
    clrscr();
    printf("ENTER THE STRING : ");
    scanf("%s",&S);
    printf("\n\nENTER THE CHARACTER TO BE REPLACED :");
    scanf(" %c",&CHR);
    printf("\n\nENTER THE REPLACEMENT CHARACTER :");
    scanf(" %c",&REPL_CHR);
    COUNT=strreplace(S,CHR,REPL_CHR);
    printf("\n\nTHE NUMBER OF REPLACED CHARACTER ARE : %d",COUNT);
    printf("\n\nTHE REPLACED STRING IS : %s",S);
    getch();
}

int strreplace(char S[],char CHR,char REPL_CHR)
{
    int I,NUM=0;
    I=0;
    while(S[I]!=NULL)
    {
    if(S[I]==CHR)
    {
        S[I]=REPL_CHR;
        NUM++;
    }
    I++;
    }
    return NUM;
}

CODE : -

  1. #include<stdio.h>
  2. void main()
  3. {
  4.     int COUNT;
  5.     char CHR,REPL_CHR,S[50];
  6.     int strreplace(char S[],char CHR,char REPL_CHR);
  7.     clrscr();
  8.     printf("ENTER THE STRING : ");
  9.     scanf("%s",&S);
  10.     printf("\n\nENTER THE CHARACTER TO BE REPLACED :");
  11.     scanf(" %c",&CHR);
  12.     printf("\n\nENTER THE REPLACEMENT CHARACTER :");
  13.     scanf(" %c",&REPL_CHR);
  14.     COUNT=strreplace(S,CHR,REPL_CHR);
  15.     printf("\n\nTHE NUMBER OF REPLACED CHARACTER ARE : %d",COUNT);
  16.     printf("\n\nTHE REPLACED STRING IS : %s",S);
  17.     getch();
  18. }
  19.  
  20. int strreplace(char S[],char CHR,char REPL_CHR)
  21. {
  22.     int I,NUM=0;
  23.     I=0;
  24.     while(S[I]!=NULL)
  25.     {
  26.     if(S[I]==CHR)
  27.     {
  28.         S[I]=REPL_CHR;
  29.         NUM++;
  30.     }
  31.     I++;
  32.     }
  33.     return NUM;
  34. }

SCREEN SHOTS :-

MCS011_Q3

MCS011_Q3_Output

Leave a Reply