Adding substring at a position of main string

Read how to display each chars position in a string
copy string without using strcpy()

We will ask users to enter two strings along with the position of the first string where the second string can be inserted.
We will create a blank string str_final to display our copied strings. We will use three loops to copy different part of the string and add them to str_final string.

First loop will read the chars of first string str1 up to the given position and insert the same to str_final string.
Second loop will read the chars of 2nd string and insert the same to final string.
Again the balance chars from the input position of first string will be read and inserted to the final string.
#include <stdio.h>
int main(){
char str1[100];
char str2[50];
char str_final[200];
int i,j,k=0,pos;

puts("enter the first string");
gets(str1);
puts("Enter Second String:");
gets(str2);
printf("Enter the position to insert");
scanf("%d",&pos);
// Print both strings ///
printf("First string: %s \n",&str1);
printf("Second string : %s \n",&str2); 

// Start first loop //

for(i=0;i<pos;i++){
 str_final[i]=str1[i];
printf("i=%d => %c \n",i,str_final[i]);
}
k=i; // Position from where final string will start
printf("\n first loop is over --\n");

for(j=0;str2[j] !='\0';j++){
    str_final[k]=str2[j];
    printf("k=%d => %c \n",k,str_final[k]);
    k=k+1;
}
printf("\n second loop is over --\n");
printf("\n %s  \n",str_final); // Final string at the end of second loop

for(i=i;str1[i] != '\0';i++){
 str_final[k]=str1[i];
 printf("k=%d => %c \n",k,str_final[k]);
 k=k+1;
}
printf("\n third is over --\n");

str_final[k]='\0';
printf("\n Final String is here : \n %s  ",str_final);
return 0;
}

Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    Post your comments , suggestion , error , requirements etc here




    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer