Showing posts with label insert. Show all posts
Showing posts with label insert. Show all posts

Friday 12 August 2016

Insert a substring to a string at specified position

Insert a substring (str) to a string (txt) at specified position (pos)


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

void main()
{
          char txt[30], str[30];
          int pos, i, k=0,m,n;
          printf("\nEnter the text: ");
          gets(txt);
          printf("\nEnter the string to be inserted: ");
          gets(str);
          printf("\nEnter the position where to be inserted: ");
          scanf("%d", &pos);
          m = strlen(txt);
          n = strlen(str);

          for(i=m-1; i>=pos; i--)
          {
                    txt[i+n] = txt[i];
          }
           i = pos;
           while(str[k] != '\0')
          {
                  txt[i] = str[k];
                   i++;
                   k++;
           }
           m = m+n;
           txt[m] = '\0';

           printf("\nThe new string is: ");
           puts(txt);
}

Output:
Enter the text: abcdefghij
Enter the string to be inserted: yyyy
Enter the position where to be inserted: 2
The new string is:  abyyyycdefghij

---------------------------------------------------------------------------------------------------
/*Method 2*/

#include<stdio.h>
void main()
{
                char txt[30],  str[30], new[40];
                int pos,  j=0, i=0, k=0;

                printf("\nEnter the text: ");
                gets(txt);
                printf("\nEnter the string to be inserted: ");
                gets(str);
                printf("\nEnter the position where to be inserted: ");
                scanf("%d", &pos);

                while(txt[i] != '\0' )
                {
                                if(i == pos)
                                {
                                                while(str[k] != '\0')
                                                {
                                                                new[j] = str[k];
                                                                j++;
                                                                k++;
                                                }
                                }
                                new[j] = txt[i];
                                j++;
                                i++;
                }
                new[j] = '\0';

                printf("\nThe new string is: ");
                puts(new);
}

Output:
Enter the text:                                            how are you
Enter the string to be inserted:                  abcde
Enter the position where to be inserted:    1

The new string is:                                      habcdeow are you