Write a C program that uses functions to perform the following operations:

  1. To insert a sub-string in to a given main string from a given position.
  2. To delete n Characters from a given position in a given string.

i) To insert a sub-string in to a given main string from a given position.

Algorithm:

Step 1: Start
Step 2: read main string and sub string
Step 3: find the length of main string(r)
Step 4: find length of sub string(n)
Step 5: copy main string into sub string
Step 6: read the position to insert the sub string(p)
Step 7: copy sub string into main string from position p - 1
Step 8: copy temporary string into main string from position p + n - 1
Step 9: print the strings
Step 10: Stop

Program:

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
   char str1[20], str2[20];
   int l1, l2, n, i;
   clrscr();
   puts("Enter the string 1\n");
   gets(str1);
   l1 = strlen(str1);
   puts("Enter the string 2\n");
   gets(str2);
   l2 = strlen(str2);
   printf("Enter the position where the string is to be inserted\n");
   scanf("%d", &n);
   for(i = n; i < l1; i++)
  {
      str1[i + l2] = str1[i];
   }
   for(i = 0; i < l2; i++)
   {
      str1[n + i] = str2[i];
   }
      str2[l2 + 1] = '\0';
   printf("After inserting the string is %s", str1);
   getch();
}

Input & Output:

Enter the string 1
sachin
Enter the string 2
tendulkar
Enter the position where the string is to be inserted 
4
After inserting the string is  sachtendulkarin

ii) To delete n Characters from a given position in a given string.

Algorithm:

Step 1: Start
Step 2: read string
Step 3: find the length of the string
Step 4: read the value of number of characters to be deleted and positioned
Step 5: string copy part of string from position to end, and (position + number of characters to end)
Step 6: Stop

Program:

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
   char str[20];
   int i, n, l, pos;
   clrscr();
   puts("Enter the string\n");
   gets(str);
   printf("Enter the position where the characters are to be deleted\n");
   scanf("%d", &pos);
   printf("Enter the number of characters to be deleted\n");
   scanf("%d", &n);
   l = strlen(str);
   for(i = pos + n; i < l; i++)
   {
      str[i - n] = str[i];
   }
   str[i - n] = '\0';
   printf("The string is %s", str);
   getch();
}

Input & Output:

Enter the string 
sachin
Enter the position where characters are to be deleted 
2
Enter the number of characters to be deleted 
2
The string is  sain