C Program to replace a character in a given string with another string

This program is used to replace any of the characters by “SPC” in the given string.

Example:

We are taking the input from the user using command line arguments.
input = $ ./a.out Sabaha
enter the character to be replaced
a
after replacing = SSPCbSPChSPC
In the above example “Sabaha” is the input string and it is recieved through the command line arguments. So argv[1] = “Sabaha” . This program will print SPC wherever the character ‘a’ is present,in this case it dispay output as SSPCbSPChSPC.

Logic:

1.Take the input from the user.
2.Use malloc and allocate memory for the given input.
3.Now the pointer(s2) created will be pointing to the allocated memory.
4.Call the function my_replace( argv[1], s2, x) by passing x, address of argv[1] and the pointer s2 .
5.The control goes to the function defination( void my_replace(char * s1, char * s2, char x)).
6.In the function defination , define another string s3[4] = “SPC” and consider two variables i , j = 0 and k.
7.Check if value at the address stored in s1 is equal to the character which has to be replaced.If yes start copying the string “SPC” into s2 else copy the *s1 (value at the address stored in s1) into s2.
8.When s1 encounters the ‘\0’ character ,stop comparing *s1 and given the given character.
9.Print the string s2.

Source code:

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void my_replace(char*,char*,char);
int main(int argc , char *argv[])
{
            int r,x;
           printf("enter the char to be replaced\n");
          scanf("%c",&x);
          r = strlen(argv[1] + strlen("SPC"));
          char *s2 = malloc(r * sizeof(char));
          my_replace(argv[1], s2, x);
          printf("%s\n",s2);
}
void my_replace(char* s1,char* s2,char x)
{
          char s3[4] = "SPC";
          int i, j = 0,k;
          for(; *s1 != '\0';s1++)
         {
                   if(*s1 == x )
                   {
                              for(k = 0;s3[k] != '\0';k++)
                             {
                                           s2[j++] = s3[k];
                            }
                }
               else
              {
                              s2[j++] = *s1;
               }
        }
}

 

This article is written by one of my student as part of their blog writing exercise.

To learn more programs on C and C++, click this link: Interview Questions

Subhash.K.U, Principal Mentor, Subhash Embedded Classes,Bangalore.

VIEW SUBHASH’s PROFILE

SUBHASH LOVES TO TEACH ! CLICK HERE !

Subhash Embedded Classes is one of the Best Embedded Systems Training Institute in Bangalore

No Comment

You can post first response comment.

Leave A Comment

Please enter your name. Please enter an valid email address. Please enter a message.