Tuesday 15 March 2022

NPTEL - WEEK 4 - ASSIGNMENT 4 - QUESTION 02

 WEEK 4 - ASSIGNMENT 4 - QUESTION 02 SOLUTION

QUESTION : 

Write a program that replaces the occurence of a given character (say c)
in a primary string (say PS) with another string (say s).

Input:
The first line contains the primary string (PS)
The next line contains a character (c)
The next line contains a string (s)

Output:
Print the string PS with every occurence of c replaced by s.

NOTE:
- There are no whitespaces in PS or s. 
- Maximum length of PS is 100.
- Maximum length of s is 10.


SOLUTION : 

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

int main()
{
    char ps[100], s[10], c, buff;
    int i=0,k=0, j=0, occ=0, len_ps, len_s, tlen;

    scanf("%s", ps);
    scanf("%c", &buff);
    scanf("%c", &c);
    scanf("%s", s);

    len_ps = strlen(ps);
    len_s = strlen(s);
    occ = 0;
    for(i=0; i<len_ps; i++)
    {
        if(ps[i] == c)
        {
            occ++;
        }
    }
    tlen = len_ps + ((len_s * occ) - occ);
   
    j = tlen;
   
    for(i=len_ps; i>0; i--)
    {
        if(ps[i-1] == c)
        {
            for(k=len_s; k>0; k--)
            {
                ps[j-1] = s[k-1];
                j--;
            }
        }
        else
        {
            ps[j - 1] = ps[i-1];
             j--;
        }
      
    }
    ps[tlen] = '\0';
    puts(ps);
    return 0;
}

COME AGAIN LEARN AGAIN !!

< iCodeBuzz />


No comments:

Post a Comment